How to find inactive objects using GameObject.Find

2020-01-29 10:33发布

I needed to find inactive objects in Unity3D using C#.

I have 64 objects, and whenever I click a button then it activates / inactivates objects for the corresponding button at runtime. How can I find inactive objects at this time?

标签: c# unity3d
4条回答
smile是对你的礼貌
2楼-- · 2020-01-29 11:10

Well, using GameObject.Find(...) will never return any inactive objects. As the documentation states:

This function only returns active gameobjects.

Even if you could, you'd want to keep these costly calls to a minimum.

There are "tricks" to finding inactive GameObjects, such as using a Resources.FindObjectsOfTypeAll(Type type) call (though that should be used with extreme caution).

But your best bet is writing your own management code. This can be a simple class holding a list of objects that you might want to find and use at some point. You can put your object into it on first load. Or perhaps add/remove them on becoming active or inactive. Whatever your particular scenario needs.

查看更多
该账号已被封号
3楼-- · 2020-01-29 11:13

You can use Predicates. Just get the gameObjects and check them whith a Predicate as below:

public List<GameObject> FindInactiveGameObjects()
{
    GameObject[] all = GameObject.FindObjectsOfType<GameObject> ();//Get all of them in the scene
    List<GameObject> objs = new List<GameObject> ();
    foreach(GameObject obj in all) //Create a list 
    {
        objs.Add(obj);
    }
    Predicate inactiveFinder = new Predicate((GameObject go) => {return !go.activeInHierarchy;});//Create the Finder
    List<GameObject> results = objs.FindAll (inactiveFinder);//And find inactive ones
    return results;
}

and don't forget using System; using System.Collections.Generic;

查看更多
4楼-- · 2020-01-29 11:16

If you have parent object (just empty object that plays role of a folder) you can find active and inactive objects like this:

this.playButton = MainMenuItems.transform.Find("PlayButton").gameObject;

MainMenuItems - is your parent object.

Please note that Find() is slow method, so consider using references to objects or organize Dictionary collections with gameobjects you need access very often

Good luck!

查看更多
别忘想泡老子
5楼-- · 2020-01-29 11:23

Although its not the correct answer, but this is what I did in my case.
1) Attach a script to (inactive) game objects and instead of setting then inactive keep it active.
2) Position them out of the scene somewhere.
3) Set a flag in the script which says inactive.
4) In Update() check for this inactive flag and skip function calls if false.
5) When needed the object, position it at the proper place and set the flag active.

It will be a bit of a performance issue but that's the only workaround I could think of so far.

查看更多
登录 后发表回答