I'm trying to avoid using GameObject.Find
during runtime to find particular GameObject components when wanting to instantiate them.
I have created a cache for the gameobjects from which I can either return the original instance or create a new instance.
Components which should only have one instance are returned by GetOriginal<UnityObject>
A new instance of an Original component is returned using GetInstanceOf<UnityObject>
public class GameObjectTools : MonoBehaviour
{
static List<Object> gameObjectCache = new List<Object>();
// This is called BEFORE Start() when the script is being loaded
void Awake()
{
// Cache any GameObject classes that are required by other classes here
gameObjectCache.Add(GameObject.Find("Timer").GetComponent<Timer>());
gameObjectCache.Add(GameObject.Find("Object Rotator").GetComponent<ObjectRotator>());
gameObjectCache.Add(GameObject.Find("Object Translator").GetComponent<ObjectTranslator>());
}
public static T GetOriginal<T>() where T : Object
{
int index = -1;
int numObjects = gameObjectCache.Count;
for (int i = 0; i < numObjects; ++i)
{
if (gameObjectCache[i].GetType() == typeof(T))
{
index = i;
break;
}
}
return index == -1 ? null : gameObjectCache[index] as T;
}
public static T GetInstanceOf<T>() where T : Object
{
var o = GetOriginal<T>();
return o == null ? null : GameObject.Instantiate(o) as T;
}
}
I'm slightly concerned that I am not approaching this problem in the right manner and was hoping for some feedback regarding my methodology.
Is there a more efficient or straightforward approach to achieve what I am trying to achieve here?
EDIT
public class Ball : MonoBehaviour
{
int lifeSpan = 1000;
void Update()
{
if (Timer.CurrentTime > lifeSpan)
GameObject.Destroy(gameObject);
}
}
public class GameObjectTools : MonoBehaviour
{
public static Ball Ball;
void Awake()
{
Ball = GameObject.Find("Ball").GetComponent<Ball>();
}
}
If I call
var ball = GameObject.Instantiate(GameObjectTools.Ball) as GameObject;
anytime after the lifespan of the ball has expired then I will get a null reference error.
How then can I ensure that this doesn't happen while still being able to create new instances from a static cache?