Try this:
using UnityEngine;
using System.Collections;
public class CrashEditor : MonoBehaviour {
void Awake() {
gameObject.AddComponent(typeof(BoxCollider));
}
}
- Create a game object in the world.
- Add the CrashEditor component to it.
- Deactivate the game object by clicking the checkbox in the inspector.
- Press play.
- Activate the game object by clicking the checkbox in the inspector.
- Notice how the box collider was not added in the inspector?
- Press stop. This will either crash the editor entirely or just return some errors if you’re lucky.
Crash verified from 3.5 up to 4.2.04f. (Did not test 4.2.1 yet.)
Oddly, this crash does not occur when you activate the object using SetActive. Editor bug to do with the inspector I suspect.
Possible workaround:
Add components in Start() instead of Awake().
BUG REPORTED
NOTE: This also happens if AddComponent is called inside OnEnable under the same circumstances.
This post is just to document the bug in case someone else has the same problem.
Workaround:
In case you need something to happen in OnEnable and you need your components added first, therefore Start() would be too late to add your components, here is a workaround:
private bool componentsCreated;
private bool deferredOnEnable;
void OnEnable() {
if(!componentsCreated) { // components don't exist yet because OnEnable ran before Start the first time the object was activated
deferredOnEnable = true; // we will wait until the end of start to actually do what we were doing to do here
return;
}
DoOnEnable();
}
void DoOnEnable() {
// Do something with created components
}
void Start() {
CreateComponents(); // create the components in start to avoid crashes
// Process OnEnable at the end of Start instead so it happens after the components have been created
if(deferredOnEnable) {
deferredOnEnable = false;
DoOnEnable();
}
}
void CreateComponents() {
gameObject.AddComponent(MyComponent);
}