无法访问其他类中的变量进行文本显示[Unity]

时间:2016-04-13 01:55:37

标签: c# methods unity3d

我有shelf.cs和GameManager.cs类。在shelf.cs中,方法displayApple将返回一个字符串。然后GameManager将访问该字符串并将其显示在文本字段中。

shelf.cs

public class shelf: MonoBehaviour
{
        //adding all the gameobjects into a list
        public List<GameObject> players;

        public string textApp ="";

        public string displayApple()
        {
            for (int i = players.Count - 1; i >= 0; i--) {
                if (players [i].name == "Apple") {
                    textApp = textApp + players [i].GetComponent<Apple> ().type + " " + players [i].GetComponent<Apple> ().colour + " " + players [i].GetComponent<Apple> ().weight;
                    textApp = textApp + "\n";
                }
            }
            long_apple= textApp;
            return long_apple;
        }
    }

然后在GameManager.cs

public class GameManager : MonoBehaviour {
    Basket bask;
    public Text text_apple; 

    // Use this for initialization
    void Start () {
        text_apple.text = bask.displayApple; //i want to call the method of displayApple to get the string returned.
        }
}

文本字段不会显示字符串,并且存在错误。

NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () (at Assets/scripts/GameManager.cs:12)

1 个答案:

答案 0 :(得分:0)

您永远不会在GameManager.cs中初始化晒太阳。

public class GameManager : MonoBehaviour {
Basket bask;
public Text text_apple; 

// Use this for initialization
void Start () {
    bask = GameObject.Find("BaskNameInHierarchy").GetComponent<Basket>()
    text_apple.text = bask.displayApple; //i want to call the method of displayApple to get the string returned.
    }
}

你也可以公开晒众public Basket bask;。然后将GameObject拖到脚本附加到的GameObject上的检查器中。

如果您尝试访问Shelf,则Basket脚本也应调用displayApple()。或者相反:private shelf bask