I have submitted this to Unity via Crash Report, but I’m posting here because I need an enlightenment/solution for this problem since it’s very important and urgent to our project.
A public field or private with SerializeField attribute in a MonoBehaviour will make Unity crash if this field is from an abstract class and someone creates a clone of the MonoBehaviour using GameObject.Instantiate and then call a method from the abstract class, even if the field is not null.
The problem happens because Unity serialize it using the abstract type instead of the actual type.
The following example illustrate this problem, Unity will crash if you hit T:
public class CloningTests : MonoBehaviour
{
[SerializeField]
private SomethingMaker SomethingMaker;
void Start()
{
SomethingMaker = new SecondObject ();
}
void OnGUI ()
{
Event ev = Event.current;
if (ev.type == EventType.KeyUp && ev.keyCode == KeyCode.T) {
CloningTests script = (CloningTests)FindObjectOfType (typeof(CloningTests));
CloningTests clone = (CloningTests)GameObject.Instantiate (script);
clone.SomethingMaker.DoSomething ();
}
}
}
[Serializable()]
public abstract class SomethingMaker
{
public abstract void DoSomething ();
}
[Serializable()]
public class SecondObject : SomethingMaker
{
public override void DoSomething ()
{
Debug.Log ("Doing something");
}
}