Unity GameObject.activeSelf, GameObject.activeInHierarchy,GameObject.SetActive和SetActiveRecursively

来源:互联网 发布:怎么注册网络域名 编辑:程序博客网 时间:2024/05/18 00:50

activeSelf(read only只读):物体本身的active状态,对应于其在inspector中的checkbox是否被勾选
activeInHierarchy(read only只读):物体在层次中是否是active的。也就是说要使这个值为true,这个物体及其所有父物体(及祖先物体)的activeself状态都为true。

一个物体要在场景中是可见的(不是隐藏的),那么不仅仅其本身的activeSelf要为true,其所有父物体(及祖先物体)的activeself状态都要为true。

总结:
activeInHierarchy状态代表物体在场景中的实际的active状态。实际上代表的是物体及其所有祖先物体的activeSelf状态。而activeSelf对应于其在inspector中的checkbox是否被勾选

activeSelf状态代表物体自身的activeSelf状态,所以当物体本身activeSelf为true,而其所有祖先物体的activeSelf状态不全为true时,这个物体的activeInHierarchy状态为false。

activeSelf==物体自身
activeInHierarchy==物体自身及其所有祖先物体==物体在场景中实际上是否激活

至于SetActive,改变的是物体自身的activeSelf状态,所以,对一个物体SetActive时,其在场景中可能不会被激活,因为其祖先物体可能存在未被激活的。
SetActiveRecursively,改变物体自身及其所有子物体的activeSelf状态,相当于对物体自身及其所有子物体调用SetActive.
由于SetActiveRecursively已过时(obsolete),未来将移除,所以,当设置一个物体及其所有子物体的active状态时,可以调用一下方法

void DeactivateChildren(GameObject g, bool a) {    g.activeSelf = a;    foreach (Transform child in g.transform) {        DeactivateChildren(child.gameObject, a);    }}

Advanced Skill :

Using Extension Method

public static class Extensions{    public static void SetactivateForAllChildren(this GameObject go, bool state)    {        DeactivateChildren(go, state);    }    public static void DeactivateChildren(GameObject go, bool state)    {        go.SetActive(state);        foreach (Transform child in go.transform)        {            DeactivateChildren(child.gameObject, state);        }    }}

Now You Can Use Like That:

public  class MyTest : MonoBehaviour {    public GameObject go;    // Use this for initialization    void Start () {        //过时        //go.SetActiveRecursively(true);        go.SetactivateForAllChildren(true);    }}

这里写图片描述
这里写图片描述
文章转自http://www.mamicode.com/info-detail-256427.html

0 0
原创粉丝点击