Hello, Im trying to do component switching in editor mode. I have component with predifined list of behaviors. And I would like to have an option to select that behavior from the editor. So I prepared MonoBehavior classes which implements IMyBehaviorInterface with required methods. Then I would like to have SerializedField in main script that can select such behavior. I
ve implemented that approach with help of
enum MovementClasses { GravityMovement, NonGravity}
[SerializeField]
MovementClasses movementClass;
void Awake()
{
playerMovement = GetComponent<IPlayerMovement>();
}
private void OnValidate()
{
switch (movementClass)
{
case MovementClasses.GravityMovement:
{
IPlayerMovement component;
if (TryGetComponent<IPlayerMovement>( out component))
{
var existingComponent = GetComponent(component.GetType());
UnityEditor.EditorApplication.delayCall += () =>
{
DestroyImmediate(existingComponent);
};
}
playerMovement = gameObject.AddComponent(typeof(GravityMovement)) as IPlayerMovement;
break;
}
case MovementClasses.NonGravity:
{
IPlayerMovement component;
if (TryGetComponent<IPlayerMovement>(out component))
{
var existingComponent = GetComponent(component.GetType());
UnityEditor.EditorApplication.delayCall += () =>
{
DestroyImmediate(existingComponent);
};
}
playerMovement = gameObject.AddComponent(typeof(NonGravityMovement)) as IPlayerMovement;
break;
}
}
}
But there is an issue , that when I start playmode , my component instance resets, and I dont have a reference in my playerMovement variable to use it. I assume that it is related to delayCall which invoked after entering playMode, but it
s the only way I found how to remove component from the inspector mode. Could you please suggest how can I fix it or maybe achive my goal another way in Unity. Thank you in advance.