首页 文章

Unity将GameObject分配给在运行时实例化的预制件

提问于
浏览
0

我有一个名为“trigger.cs”的脚本 . 此脚本附加到预制件中的对象 . 预制件在运行时实例化 .

现在这就是我想要的:
enter image description here

这是我想要分配而没有拖放的游戏对象 .
enter image description here

另外,如果我能以某种方式硬编码“死亡菜单”,这也是一个解决方案 .

这是我的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 回答

  • 1

    它不起作用,因为你需要在 function 中初始化 deathMenu 变量 . 您不能在函数外使用 GameObject.Find("Death Menu"); . 在房产中使用它也很好 . 只要在使用 deathMenu 变量之前调用函数,任何函数都可以正常运行 . AwakeStart 函数用于这样的事情 .

    此外, GameObject.Find("Death Menu"); 返回GameObject而不是脚本或组件 . Death deathMenu 应为 GameObject deathMenu

    这应该这样做:

    public GameObject deathMenu;
    
    void Start()
    {
        deathMenu = GameObject.Find("Death Menu");
    }
    

    现在,如果您实际上有一个 Death 脚本附加到您的"Death Menu" GameObject并且您想要访问它,则需要使用 GetComponent 在找到"Death Menu" GameObject后获取脚本 .

    public Death deathMenu;
    
    void Start()
    {
        deathMenu = GameObject.Find("Death Menu").GetComponent<Death>();
    }
    

相关问题