简体   繁体   English

如何在 Unity3D 中引用非活动的 GameObject?

[英]How to reference an inactive GameObject in Unity3D?

I'm trying to access an inactive gameobject that is the child of another gameobject, but I'm having trouble.我正在尝试访问作为另一个游戏对象的子级的非活动游戏对象,但我遇到了问题。

Right now I'm using this line of code to try to access the inactive child gameobject and set it active:现在我正在使用这行代码尝试访问不活动的子游戏对象并将其设置为活动状态:

go.GetComponentInChildren<EnemyMover>().gameObject.SetActive(true);

I am getting a null ref error.我收到一个空引用错误。

So how can I reference an inactive gameobject?那么我怎样才能引用一个非活动的游戏对象呢?

You can use GetComponentsInChildren<EnemyMover>(true) , where the true indicates you want to include components on inactive game objects.您可以使用GetComponentsInChildren<EnemyMover>(true) ,其中 true 表示您希望在非活动游戏对象上包含组件。 Then you can use .First() (or any of the variants Linq offers) to get a single result.然后您可以使用.First() (或 Linq 提供的任何变体)来获得单个结果。

I know Im a bit late, but in case somebody is still wondering how to find an inactive GameObject here is an example:我知道我有点晚了,但如果有人仍然想知道如何找到一个不活动的游戏对象,这里是一个例子:

GameObject[] objects = Resources.FindObjectsOfTypeAll(); GameObject[] 对象 = Resources.FindObjectsOfTypeAll();

    foreach (GameObject go in objects)
    {
        if (go.name.Equals("Your component")){
            go.SetActive(true);
        }
    }

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

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