A generic "Find GameObject From Path" method.

Hi.

I’m trying to make a small generic function to ease the exception handling and error messages when getting a gameObject from a path.

I’ve made this:

	public static class GameObjectHelper
	{
		public static Component GetGameObjectFromPath<T>(string path)
		{
			GameObject gameObject = GameObject.Find(path);
			Component c;
			if (gameObject != null)
			{
				c = gameObject.GetComponent(typeof(T));
			}
			else
			{
				throw new Exception("GameObject not found in " + path + ".");
			}
			
			return c;
		}
	}

So this works if I do something like this:

SomeController someController = (SomeController) GameObjectHelper.GetGameObjectFromPath<SomeController>("/Menu/WorldNode/SceneObjects/SomeScene");

But I would like to do it without the type cast. Or generally know if I can make it better or more optimal.

Ideally it would be great if I could do just this:

SomeController someController = GetGameObject("/the/path");

… with no casts or anything at all. But I am not sure that would be possible.

I don’t believe that it is possible. C# is strongly typed and requires the type to be expressed, using a template is the best way as your example.

 t = (T)gameObject.GetComponent<T>();

which is pretty much what you are doing

… I would advise getting used to how C# works.
You could look at #define to short cut it but that only works for one type…

Assuming everything else is correct, you want to change

public static Component GetGameObjectFromPath<T>(string path)

to:

public static T GetGameObjectFromPath< T >(string path)

However, you will still have to declare what you expect the object to be with:

GameObjectHelper.GetGameObjectFromPath<SomeController>("/Menu/WorldNode/SceneObjects/SomeScene");

but that will stop you needing a cast.

Also note that there is a generic version of GetComponent:

GetComponent<SomeComponent>();

I believe you could avoid expressing the type if you refactor it to be more like:

public static bool TryGetComponentFromPath<T>(string path, out T Component)

because that way you would be strictly defining “T” when you call the function. Also note that if you limit the declaration like

public static bool TryGetComponentFromPath<T>(string path, out T Component) where T : class

you will be able to return null instead of throwing an exception (if preferred)