1
\$\begingroup\$

For example:

[System.Serializable]
public class A
{
    [SerializeField]
    public int x;
}
public class TestA : MonoBehaviour
{
    [SerializeField]
    public A a = new A();
}

[System.Serializable]
public class B : A
{
    [SerializeField]
    public int y;
}
public class TestB : TestA
{
    // Not legal, I know. Considering Unity forbids the use of constructors in 
    // monobehaviour classes, I have no idea how I'd do this.
    a = new B();
}

Given that this MonoBehaviour class "TestA" exposes an "A" object, I'd like to override this default value so that when a MonoBehaviour of type "TestB" is attach to a game object in the editor, an object of type "B" is exposed.

Perhaps I'm better off looking into creating custom property drawers, but I'm wondering if there is a way to do this with the default editor.

\$\endgroup\$
2
\$\begingroup\$

There are some problems with your approach.

Unity doesn't support serialization of polymorphic custom classes not derived from ScriptableObject or MonoBehaviour.

In other words, it doesn't matter where and how you initialized a field, if B if an instance of A it will be sliced of (or won't be serialized at all I don't remember exactly I need to check).

Similar to this answer.

A clarification:

a = new B();

This is legal. You don't instantiate certain classes using constructors (such as MonoBehaviours) becasue those are resources allocated in the unmanaged C++ side of the engine. MonoBehaviour are just C# wrappers for the relative components. For everything whose lifetime and ownership is just managed by mono runtime, than you can use constructors.

\$\endgroup\$
  • \$\begingroup\$ So, basically it has to be a MonoBehaviour component, and attached manually in the editor? \$\endgroup\$ – Ben May 1 '15 at 3:49
  • \$\begingroup\$ A MonoBehaviour or ScriptableObject. Not necessary attached by hand. You can use CreateInstance and do it by code. \$\endgroup\$ – Heisenbug May 1 '15 at 10:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.