引言
昨天在工作中调用GameObject.active时看到有这样的提示”GameObject.active is obsolete. Use GameObject.SetActive(), GameObject.activeSelf or GameObject.activeInHierarchy.”发现Unity推荐使用activeInHierarchy和activeSelf的方法来使用。
区别何在?
从注释中看,activeInHierarchy表示在场景中的active状态,active仅代表当前gameobject的active状态。
动手试验
创建如下测试对象
将测试代码挂载在UIRoot上
using UnityEngine;
using System.Collections;
public class VisibleTest : MonoBehaviour {
public GameObject parent, child;
// Use this for initialization
void Start () {
if (parent != null)
{
Debug.Log("parent activeInHierarchy: " + parent.activeInHierarchy + ", parent activeSelf: " + parent.activeSelf);
}
if (child != null)
{
Debug.Log("child activeInHierarchy: " + child.activeInHierarchy + ", child activeSelf: " + child.activeSelf);
}
}
// Update is called once per frame
void Update () {
}
}
第一种情况:
parent[active] child[active]
parent和child的两种状态都为true。
第二种情况:
parent[inactive] child[active]
这是parent的两种状态都为false,而child的activeHierarchy为false,activeSelf为true。此时的child并步可见,但是自身的active属性还是true。
结合上述的例子,可以看出activeHierarchy可以理解为场景中的可见状态。如果某个对象在场景中不可见,对应的activeHierarchy和activeSelf属性一定为false,而该对象的子对象的activeHierarchy也为false,其activeSelf属性却取决于自身的状态,不依赖于父对象。