Hi,
I wrote this piece of code to speed up checking existance of singletons without actually changing the singletons implementation and without of course checking their Instance property or the non-accessible _instance private static variable.
using UnityEngine;
using System.Collections;
public static class FNSUtils {
public static bool ExistsInSceneOrError(this System.Type type)
{
if (GameObject.FindObjectOfType(type) != null)
return true;
else
{
Debug.LogError("Couldn't find a " + type.ToString() + " in the scene. Add it, save the scene and reload it");
return false;
}
}
}
In this way I could simply do a check like GameManager.ExistsInSceneOrError() and return a value, without the hassle to write this for every Manager or Singleton.
But, it doesn’t seem to work.
Now, is there a way to do this with the method extensions? Which other solution would you propose? A static utility class with a static method?
I assume you've tried: GameObject.FindObjectOfType(typeof(type))
– Bieere"But, it doesn't seem to work." Need more details. Looks ok to me, at fist glance. Is it the FindObjectsOfType that fails? Alternatives: Create a Static Class that contains a Dictionary - and have your singletons register themselves in there. Then when you need to check for existence, it should be a much shorter list to look through than all scene objects, and you can just use dictionary.Contains to see if it exists. Though I'd also return the looked-up gameobject or null, rather than a bool.
– Glurth