简体   繁体   English

禁用对象时,.activeInHierarchy的输出仍然为true

[英]Output from .activeInHierarchy still true when object is being disabled Unity

I'm currently learning the basics of Unity and, as always when one is learning something new , I'm a bit stuck. 我目前正在学习Unity的基础知识,并且像往常一样,当人们学习新东西时 ,我有点卡住了。

There is a falling cube that is being set inactive when it collides with something. 有一个下降的多维数据集与某物体碰撞时被设置为不活动状态。 I was planning on making a parent script that checks if the cube is active or inactive. 我打算制作一个父脚本,以检查多维数据集是否处于活动状态。 And when it's inactive, it outputs the state of the boolean eActive in the console. 当它处于非活动状态时,它将在控制台中输出布尔eActive的状态。

But whenever the falling cube is colliding with something it does disappear, but the output of the boolean is still true. 但是,只要下降的多维数据集与某些东西碰撞,它的确会消失,但是布尔值的输出仍然为真。

Both scripts: 这两个脚本:

Enemy.cs Enemy.cs

using UnityEngine;

public class Enemy : MonoBehaviour {

GameObject enemy;

// Use this for initialization
void Start () 
{
    enemy = GameObject.Find("Enemy");
    enemy.SetActive(true);
}

public void OnCollisionEnter(Collision collision)
{
    enemy.SetActive(false);
}
}

EnemySpawn.cs EnemySpawn.cs

using UnityEngine;

public class EnemySpawn : MonoBehaviour {

GameObject enemy;
public bool eActive ;

// Use this for initialization
void Start () 
{
    enemy = GameObject.FindWithTag("Enemy");
    eActive = enemy.activeInHierarchy;
    Debug.Log(eActive);
}

// Update is called once per frame
void Update () 
{
    Destroyed();
}

void Destroyed()
{
    if (!eActive)
    {
        Debug.Log(eActive);
    }
}
} 

Would love to hear what I'm doing wrong and if there are better ways to do these kind of things in Unity! 很想听听我做错了什么,如果有更好的方法在Unity中做这些事情!

Big thanks in advance :) 预先非常感谢:)

There are two problems in your code 您的代码中有两个问题

1-) You assign a value to eActive in Start and never update it when object is disabled. 1-)您在StarteActive分配了一个值, eActive在禁用对象时从不更新它。 So it is always true because it is never updated. 因为它永远不会更新,所以它总是正确的。

2-) Use GameObject.activeSelf instead of activeInHierarchy since you just enable and disable the object and your object has no parents! 2-)使用GameObject.activeSelf代替activeInHierarchy因为你刚刚启用和禁用对象和你的对象没有父母! . Also you do not need a boolean variable to hold activeSelf or care about updating it. 另外,您不需要布尔变量即可保存activeSelf或关心对其进行更新。 Unity does this for you just use it. Unity只是为您使用而已。

So your Destroy method should look like this: 因此,您的Destroy方法应如下所示:

void Destroyed()
{
    if (!enemy.activeSelf)
    {
        Debug.Log("Enemy is not active");
    }
}

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM