Using Reflection for accessing arbitrary GameObject properties

Hi there,

I’m trying to use C#'s Reflection capabilities to access GameObject properties via strings, so I can address arbitrary objects in the game using URLs.

The problem is that I get a null FieldInfo when I try something like this:

GameObject cubeGameObject = GameObject.Find("Cube");

if (cubeGameObject != null)
{
	FieldInfo field = cubeGameObject.GetType().GetField(
		"transform", BindingFlags.Instance | BindingFlags.Public);
	
	print("field == null? " + (field == null));
}

Is there a particular way I should be using Reflection within Unity?

Thanks,

Ahonek

Never mind, I answered my own question. I guess I should have looked harder at MSDN before I posted!

It turns out that Transform is a property of the GameObjects, and not a field. So if you do the same thing using PropertyInfo and GetProperty, you’ll come out successful.

Maybe you are already aware, but reflection is quite slow. So be careful of using it in Update() FixedUpdate() OnGui() and coroutines. good luck!

1 Like