There are likely better ways to do this, but it will suffice for simple situations where you wish to store handles to gameobjects (often UI items) and then be able to get handle references by gameobject name lookup. At the very least, those of you who are new to coding will find this simple class an example of how to track gameobject handles so that you can interact with them after you've disabled them and can no longer use the Find or FindChild functions to get a reference.
This class script should be attached to any gameobject that you might want to get a reference by name later on.
using UnityEngine;
using System.Collections;
public class GlobalGameObjectTracker : MonoBehaviour {
// This class is used to get references to unique objects within the hierarchy by unique name
private static Hashtable _globalGameObjectLookupByNameHashtable
= new Hashtable
();
// Use this for initialization
void Awake () {
if (_globalGameObjectLookupByNameHashtable.Contains(this.name))
{
Debug.LogError("Duplicate GameObject named: " + this.name +"\nCannot add item to GlobalGameObjectTracker hashtable.");
return;
}
_globalGameObjectLookupByNameHashtable.Add(this.name, this.gameObject);
}
public static GameObject GetGameObjectByName(string gameObjectName)
{
if (_globalGameObjectLookupByNameHashtable.Contains(gameObjectName))
{
return (GameObject) _globalGameObjectLookupByNameHashtable[gameObjectName];
}
Debug.LogError("Could not find GameObject named: " + gameObjectName + "\nCannot find item in GlobalGameObjectTracker hashtable.");
return null;
}
}
In any other script you can then call GlobalGameObjectTracker.GetGameObjectByName(
unique_object_name) to get a gameobject variable handle.