Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
So, basically it has to be a MonoBehaviour component, and attached manually in the editor? –  Ben May 1 at 3:49
    
A MonoBehaviour or ScriptableObject. Not necessary attached by hand. You can use CreateInstance and do it by code. –  Heisenbug May 1 at 10:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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