- Home /
Modify GameObject Components via C# Reflection
Hi,
I am currently trying to develop a tool for Unity like Animation and I want to use the C# Reflection to make it dynamic.
Up to now I've been able to get these Properties and to read their values but I don't succeed in modifying its values.
I use the PropertyInfo.SetValue method to modify the Transform Component of this GameObject, the data is correctly modified but my GameObject does not move and the values in the Inspector do not change. If i get my value back right away it's still the one i put before If i get my GameObject and check its transform, it's changing as i want too (but still not in the scene or in the inspector).
IMPORTANT: I'm doing it in editor mode, without inheriting from MonoBehaviour or Editor (but still when i get the GameObject it has my modifications).
Can anyone point me on the right direction about that ? Thank you !
Answer by DalinCriid · Jan 21, 2014 at 03:30 PM
Ok, It looks like some properties cannot be modified this way, for example the transform.position cannot but the transform.localPosition does the trick.
transform.position property info is : PropertyInfo.CanRead && PropertyInfo.CanWrite but it still not editable.
Answer by HarvesteR · Aug 18, 2015 at 02:55 PM
I'm not sure if Reflection is the best approach here. I'm assuming you want to have control over GameObject properties without having to attach MonoBehaviours to the objects themselves?
I would suggest having a look at C#'s extension methods. You can write a class (not mb-subclass, mind) with methods like this:
public static class GameObjectExtension
{
public static void DoStuffMyWay(this GameObject go)
{
// do stuff to 'go' your way
}
}
And that will appear as if it were a member of GameObject, meaning you get to call it like this:
GameObject myObj;
//...inside some method
myObj.DoStuffMyWay();
I'm not sure what exactly you're trying to accomplish, but if you want to add extra methods to existing types without subclassing them, extension methods are the way to go!
Cheers
Your answer
Follow this Question
Related Questions
Bind to OnWillSaveAssets and force to save my scene 0 Answers
Updating object on inspector value changes in editor 1 Answer
object field decides when it wants to work,Why does my list clear itself 0 Answers
Multiple Cars not working 1 Answer
DestroyImmediate(component.gameObject) destroys component but not gameObject 1 Answer