Unable to access variable in other class for text

2019-09-21 16:15发布

I have class of shelf.cs and GameManager.cs. In shelf.cs, the method displayApple will return a string. Then the GameManager will access the string and display it in Text field.

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;
        }
    }

then in 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.
        }
}

The text field wont display the string and there are errors.

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

1条回答
叼着烟拽天下
2楼-- · 2019-09-21 17:15

You are never initializing the bask in 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.
    }
}

You can also make the bask public public Basket bask;. Then drag a GameObject into the inspector on the GameObject that the script is attached to.

Also the Shelf script should be called Basket if you're trying to reach displayApple(). Or the other way around: private shelf bask.

查看更多
登录 后发表回答