- Home /
Is there any way to successfully cast a UnityEngine.Object to a System.Object?
From what I know there isn't.
But I'm asking just in case maybe one of you guys knows a hack to get this to work somehow.
A typical need for this cast, is when you have a SerializedProperty
that's referencing a System.Object
- I haven't found any way to get the typed reference in this case because SP.objectReferenceValue
returns a UE.Object, that's why I'm asking about the cast.
i.e.
[System.Serializable]
public class SomeClass { public void doStuff() { } }
public class Test : MonoBehaviour { public SomeClass someClassObject; }
[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
override void OnInspectorGUI()
{
SerializedProperty sp_someClassObject = serializedObject.FindProperty("someClassObject");
(magical cast on sp_someClassObject).doStuff();
}
}
Any ideas?
Thanks!
That's pretty awesome thanks! - But if I wanted to get an object directly, I would just get it via 'target' - I mean why reflection?
in my case just (target as Test).doStuff();
ins$$anonymous$$d of (GetValue(target, "myClassObject") as Test).doStuff();
In both cases we got a direct reference to the object, and we're not benefiting from SerializedProperties anymore.
(unless I'm missing something and doing it your way will still make us somehow benefit from SPs (undo, redo, etc))
$$anonymous$$y way let's you get it when you only have a serialized property - that happens most often in the case of PropertyDrawers, though I've ended up using it elsewhere to make code which is re-usable across a range of objects. You're right, if you know what you've got, it's faster and clearer to do it directly.
Thanks. Finally, can you shed some light on GetParent? what is 'parent' in this context? and what kind of useful things I could do with this parent?
So that's really the PropertyDrawer thing - a Drawer knows the individual property type etc, but it has no idea what owns that property. I (and a few other people) have had problems where we need to understand the context of the property to create a useful drawer.
So GetParent returns the object that owns the property that is currently being used.
Answer by whydoidoit · Feb 22, 2014 at 10:41 AM
As far as I know you can't do that - the serialized properties of your custom classes end up in the stream of serialization rather than having object reference values. It appears that this causes issues around the duplication of shared objects in the serialization at times.
This: http://answers.unity3d.com/questions/425012/get-the-instance-the-serializedproperty-belongs-to.html might help as it uses reflection to map property accesses to the names in the serialization stream to return the actual object being reference (or its parent).