【问题标题】:Unity assign GameObject to a prefab which is instantiated at run timeUnity 将 GameObject 分配给在运行时实例化的预制件
【发布时间】:2017-05-05 05:17:49
【问题描述】:

我有一个名为“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 !");
    }
}

【问题讨论】:

    标签: c# unity3d unity5


    【解决方案1】:

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

    另外,GameObject.Find("Death Menu"); 返回一个游戏对象,而不是脚本或组件。 Death deathMenu 应该是 GameObject deathMenu

    应该这样做:

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

    现在,如果您确实有一个Death 脚本附加到您的“死亡菜单” GameObject 并且您想要访问它,您需要在找到后使用GetComponent 获取脚本“死亡菜单” GameObject。

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

    【讨论】:

    • 好的...我已经尝试了这两个...确实,nt显示任何错误...但是当我运行游戏时它显示“NullReferenceException:对象引用未设置为对象的实例”
    • 现在让我们关注第一个。 deathMenu = GameObject.Find("Death Menu"); 导致 NullReferenceException?你把它放在Start 函数中了吗?如果是的话,你能把它放在Awake函数中吗?
    • 第一个工作正常...没有任何错误...但由于某种原因它仍然是空的...空的意思是这样的:i.stack.imgur.com/99cfl.png
    • 我应该把完整的代码发给你的......当物体撞到对撞机时,我也会用...... void OnTriggerEnter (Collider othercollider){ Debug.Log ("You是死的 !”);死亡菜单.ToggleMenu (); }
    • 对不起,我认为你在撒谎。我的回答中的第一个示例无法为您提供您在屏幕截图中发布的内容。告诉我到底发生了什么。你正在尝试第二个例子并告诉我第一个没有做任何事情......
    猜你喜欢
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2021-10-27
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多