Cannot get the position the GameObject where the script is attach

时间:2018-02-26 17:59:09

标签: c# unity3d

I have a problem when i'm referencing the game Object :

Wolf is a class where pos is a Public vector3 and the error occur at wolf.pos = this.transform.position;

Here the code:

 public class Hunter : MonoBehaviour {

 Wolf wolf;
 SpawnSheep meat;
 public GameObject hunter;
 // Use this for initialization
 void Start () {
     meat = FindObjectOfType<SpawnSheep>();
     wolf.pos = this.transform.position;
 }

 // Update is called once per frame
 void Update () {
     wolf.pos = this.transform.position;
     for (int x = 0; x < meat.sheeps.Length; x++)
     {
         Debug.DrawLine(wolf.pos, meat.sheeps[x].pos, Color.red);
     }  
 }

What did i do wrong? Is "this" not allowed in unity ? thanks in advance

1 个答案:

答案 0 :(得分:0)

您需要初始化wolf变量。如果Wolf类是单行为,则不能随意创建新实例。如果要通过预制件上的检查员设置wolf变量,请将其设为public[System.Serializable]字段,并在Hunter的检查员中设置参考。否则,你需要一些方法来创造狼

  • wolf = GameObject.Instantiate<Wolf>(WolfPrefab)
  • 获取参考:wolf = FindObjectOfType<Wolf>()(不推荐用于 表现原因)
  • 从另一个功能传递它。