I want to create different types of platforms for my game, and they are currently all in different prefabs. This works fine, but it is just taking so long to search for the prefab, dragging it in, and maybe if I dragged the wrong one into the scene, I would need to create a new platform from scratch.
My idea is that you have a custom inspector for a script that sits on an example platform, and have an enum to choose what kind of platform is placed. This idea worked until I tried to delete / add components that are not needed for the platform (A spike platform does not need a script to destroy it when clicked, while a destructable platform does not need a spike script). Right now I don't need the custom inspector, but I will add it in the future.
When I try to run this script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformTypeChanger : MonoBehaviour
{
enum PlatformType { Default, Destruckt, Spike, HingeJoint};
[SerializeField] PlatformType platformType;
private void OnValidate()
{
switch (platformType)
{
case PlatformType.Default:
Default(); break;
case PlatformType.Destruckt:
Destruct(); break;
}
}
void Default()
{
Destroy(GetComponent<Spike>());
}
void Destruct()
{
if (!GetComponent<Spike>())
{
gameObject.AddComponent<Spike>();
}
}
}
I get error:
Destroy may not be called from edit mode! Use DestroyImmediate instead.
Destroying an object in edit mode destroys it permanently.
UnityEngine.Object:Destroy (UnityEngine.Object)
PlatformTypeChanger:Default () (at Assets/PlatformTypeChanger.cs:23)
PlatformTypeChanger:OnValidate () (at Assets/PlatformTypeChanger.cs:15)
Destroy may not be called from edit mode! Use DestroyImmediate instead.
Destroying an object in edit mode destroys it permanently.
UnityEngine.Object:Destroy (UnityEngine.Object)
PlatformTypeChanger:Default () (at Assets/PlatformTypeChanger.cs:23)
PlatformTypeChanger:OnValidate () (at Assets/PlatformTypeChanger.cs:15)
Destroy may not be called from edit mode! Use DestroyImmediate instead.
Destroying an object in edit mode destroys it permanently.
UnityEngine.Object:Destroy (UnityEngine.Object)
PlatformTypeChanger:Default () (at Assets/PlatformTypeChanger.cs:23)
PlatformTypeChanger:OnValidate () (at Assets/PlatformTypeChanger.cs:15)
[Worker1] Destroy may not be called from edit mode! Use DestroyImmediate instead.
Destroying an object in edit mode destroys it permanently.
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
If I Change Destroy() to DestroyImmediate() I get this error:
Destroying components immediately is not permitted during physics trigger/contact, animation event callbacks, rendering callbacks or OnValidate. You must use Destroy instead.
UnityEngine.StackTraceUtility:ExtractStackTrace ()
PlatformTypeChanger:Default () (at Assets/PlatformTypeChanger.cs:23)
PlatformTypeChanger:OnValidate () (at Assets/PlatformTypeChanger.cs:15)
So I should neither use Destroy() nor DestroyImediate() ? What other methods are there?