我有一个名为“trigger.cs”的脚本 . 此脚本附加到预制件中的对象 . 预制件在运行时实例化 .
现在这就是我想要的:
这是我想要分配而没有拖放的游戏对象 .
另外,如果我能以某种方式硬编码“死亡菜单”,这也是一个解决方案 .
这是我的trigger.cs文件
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class trigger : MonoBehaviour {
public Text scoreText;
public Death deathMenu;
//the line below is commented because its not working for me and just throws an error.
//public Death deathMenu = GameObject.Find("Death Menu");
void Start(){
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter (Collider othercollider){
Debug.Log ("You Are Dead !");
}
}
1 回答
它不起作用,因为你需要在 function 中初始化
deathMenu
变量 . 您不能在函数外使用GameObject.Find("Death Menu");
. 在房产中使用它也很好 . 只要在使用deathMenu
变量之前调用函数,任何函数都可以正常运行 .Awake
或Start
函数用于这样的事情 .此外,
GameObject.Find("Death Menu");
返回GameObject而不是脚本或组件 .Death deathMenu
应为GameObject deathMenu
这应该这样做:
现在,如果您实际上有一个
Death
脚本附加到您的"Death Menu" GameObject并且您想要访问它,则需要使用GetComponent
在找到"Death Menu" GameObject后获取脚本 .