【问题标题】:Trouble with missing Reference after gameObject is destroyed破坏游戏对象后缺少参考的问题
【发布时间】:2015-01-24 06:33:53
【问题描述】:

在我的游戏中,假设 npc 攻击并摧毁了一个房屋,该房屋被指定为脚本中的目标,但是当房屋被摧毁时,错误提示缺少参考,我预计会发生这种情况。 ..

但是我该如何解决这个问题?有没有办法在gameObject被销毁后禁用目标变量?

这段代码在npc脚本上

void Start () {

    force = 1000;
    enemyHealth = 100;
    enemyAttack = 20;
    enemyDefense = 2;
    bigFont= new GUIStyle();
    bigFont.fontSize = 20;

    target = GameObject.FindGameObjectWithTag("Player").transform;
    targetHouse = GameObject.FindGameObjectWithTag("house").transform;



    animator = GetComponent<Animator>();
}

这是在房子脚本上

void Update () {
    if(houseHp<= 0){
        Destroy(GameObject.FindWithTag("house"));
    }
}

【问题讨论】:

    标签: c# unity3d destroy


    【解决方案1】:

    您可以检查null并避免该问题。

    GameObject temp = GameObject.FindGameObjectWithTag("house");
    
    if(temp != null)
       targetHouse = temp.transform;
    

    所以当house 被销毁时FindGameObjectWithTag() 将返回null

    【讨论】:

    • 我尝试插入此代码,但它不起作用,只是为了澄清一下,看看我是否做得对://我声明变量 temp public GameObject temp; //然后在开始时赋值 void Start () { temp = GameObject.FindGameObjectWithTag("casa"); } //if 语句必须插入到哪里?注意:我使用 FSMStates 和枚举
    • @GabrielFerraz temp 应该在我放的地方声明,在像 Start()Update() 这样的函数中。这意味着您可以将我的代码放在您已经执行此代码的任何位置:targetHouse = GameObject.FindGameObjectWithTag("house").transform;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多