DEV Community

KENTO⚽️XR Engineer😎
KENTO⚽️XR Engineer😎

Posted on

【Unity】How to refer to a gameobject sets DontDestroyOnLoad and inactive?

Intro

Unity has any kind of ways to refer arbitrary gameobject.

For instance, SerializeFieled,GameObject.Find("name").

But, if you need to refer arbitrary gameobject that sets DontDestroyOnLoad and inactive, you can not use GameObject.Find("name").

Or, there is the situation to not be able to use SerializeFieled.

Sample Code

private GameObject _empty;

void Start()
{
    //Create gameobject as DontDestroyOnLoadGameObject
    if (_empty == null)
    {
        _empty = new GameObject(string.Empty);
        DontDestroyOnLoad(_empty);
    }

    var dontDestroyOnLoadGameObjectList = new List<GameObject>();

    //Besause DontDestroyOnLoad is included Scene, it gets from GameObject.scene.
    var dontDestroyOnLoadGameObjectRootList = _empty.scene.GetRootGameObjects().ToList();
    foreach (var root in dontDestroyOnLoadGameObjectRootList)
    {
        dontDestroyOnLoadGameObjectList.AddRange(GetAll(root));
    }

    dontDestroyOnLoadGameObjectList.Any(go => go.TryGetComponent(out MyComponent component));

    //Some kind of processing
}


/// <summary>
/// Return all object of tree.
/// </summary>
private List<GameObject> GetAll(GameObject root)
{
    var allChildren = new List<GameObject>();
    GetChildren(root, ref allChildren);
    return allChildren;
}

/// <summary>
/// Add child to list from parent.
/// </summary>
private void GetChildren(GameObject obj, ref List<GameObject> allChildren)
{
    var children = obj.GetComponentInChildren<Transform>();
    if (children.childCount == 0)
    {
        return;
    }

    foreach (Transform ob in children)
    {
        allChildren.Add(ob.gameObject);
        GetChildren(ob.gameObject, ref allChildren);
    }
}

private void OnDisable()
{
    DestroyImmediate(_empty);
}
Enter fullscreen mode Exit fullscreen mode

Tips

Because DontDestroyOnLoad is included Scene, it gets from GameObject.scene.

At first, create temporary gameobject and set DontDestroyOnLoad.
Second,search all of gameobject that has specific Component.
You can search in the scene that exist temporary gameobject.

It means to be able to search a gameobject in DontDestroyOnLoad.

Other Resources

DontDestroyOnLoadのGameObjectを列挙する
全ての子要素を取得する(子要素の子要素の子要素の‥)

Top comments (0)