-4
完整的警告信息:为什么在统一中我得到警告:您正试图使用'new'关键字创建MonoBehaviour?
您正试图使用'new'关键字创建MonoBehaviour。这是不允许的。 MonoBehaviours只能使用AddComponent()添加。或者,你的脚本就可以在所有
从个ScriptableObject或没有基类继承,在这两个脚本我不使用“新”的关键字:
的DetectPlayer脚本:
using UnityEngine;
using System.Collections;
using System.Reflection;
public class DetectPlayer : MonoBehaviour {
GameObject target;
int counter = 0;
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Platform")
{
Debug.Log("Touching Platform");
//GameObject findGo = GameObject.Find("ThirdPersonController");
//findGo.transform.parent = null;
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "OnTop Detector")
{
counter = 0;
Debug.Log("On Top of Platform");
target = GameObject.Find("Elevator");
GameObject findGo = GameObject.Find("ThirdPersonController");
GameObject findGo1 = GameObject.Find("Elevator");
findGo.transform.parent = findGo1.transform;
StartCoroutine(playAnim(target));
}
}
void OnTriggerExit(Collider other)
{
GameObject findGo = GameObject.Find("ThirdPersonController");
findGo.transform.parent = null;
}
IEnumerator playAnim(GameObject target)
{
Animation anim = target.GetComponent<Animation>();
foreach (AnimationState clip in anim)
{
// do initialisation or something on clip
clip.speed = 1;
}
while (true)
{
if (counter == 1)
break;
//Play Up Anim
anim.Play("Up");
//Wait until Up is done Playing the play down
while (anim.IsPlaying("Up"))
{
yield return null;
}
//Now Play Down Anim
anim.Play("Down");
//Wait until down is done Playing
while (anim.IsPlaying("Down"))
{
yield return null;
}
yield return null; //Make sure there is no freezing
//Return to the top of the while|true loop
counter++;
}
}
void OnGUI()
{
GUI.Box(new Rect(300, 300, 200, 20),
"Times lift moved up and down " + counter);
}
}
电梯脚本:
using UnityEngine;
using System.Collections;
public class Lift : MonoBehaviour {
private bool pressedButton = false;
private bool isElevatorUp = false;
GameObject target;
DetectPlayer dp = new DetectPlayer();
void OnMouseOver()
{
pressedButton = true;
}
void OnMouseExit()
{
pressedButton = false;
}
void OnMouseDown()
{
if(isElevatorUp == false)
{
target = GameObject.Find("Elevator");
target.GetComponent<Animation>().Play("Up");
isElevatorUp = true;
}
else
{
target = GameObject.Find("Elevator");
target.GetComponent<Animation>().Play("Down");
isElevatorUp = false;
}
}
void OnGUI()
{
if(pressedButton == true)
{
GUI.Box(new Rect(300, 300, 200, 20), "Press to use lift!");
}
}
}
你绝对使用'new'关键字:'DetectPlayer DP =新DetectPlayer();当您尝试创建''MonoBehavior团结 – Serlite
不喜欢使用'new'派生的对象。它希望你使用'Instantiate'来代替它的内部管理工作。 – Cody