• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

没办法访问其他类别的变量来显示文本[Unity]

用户头像
it1352
帮助1

问题说明

我有类的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)

正确答案

#1

您永远不会在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.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfkehi
系列文章
更多 icon
同类精品
更多 icon
继续加载