无法访问其他类别的变量来显示文本[Unity] [英] Unable to access variable in other class for text display [Unity]

查看:54
本文介绍了无法访问其他类别的变量来显示文本[Unity]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后在GameManager.cs中

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)

推荐答案

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

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

您还可以公开晒太阳public Basket bask;.然后将一个GameObject拖到脚本附加到的GameObject上的检查器中.

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.

如果您要访问displayApple(),则Shelf脚本也应称为Basket.或相反:private shelf bask.

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

这篇关于无法访问其他类别的变量来显示文本[Unity]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆