没办法访问其他类别的变量来显示文本[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
.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfkehi
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20