- Home /
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.
Answer by vbbartlett · Jan 22, 2013 at 10:28 PM
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...
Since no one else gave input I must suppose your answer is correct. Until someone proves you wrong I accept this answer :-)
Answer by Tarlius · Mar 19, 2013 at 09:13 AM
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)
Your answer
Follow this Question
Related Questions
Get the child gameObject of a parent and not the Transform 4 Answers
enable and disable boxcollider (whats wrong with my script?) 2 Answers
Obtaining an array of positions from an array of gameobjects 2 Answers
Only change a variable on the instaniated object not the prefab. 0 Answers
fix script to get C# var from another object instead of object this script is attached to 2 Answers