- Home /
Instantiate GameObject on Enum Selection from Inspector
I'm wondering how to go about instantiating (or destroying) a new GameObject when a specific enum value is selected from it's dropdown menu in the Inspector window, prior to run-time.
Does anyone know how to go about doing this?
Thanks!
Answer by TreyH · Apr 01, 2016 at 05:59 PM
This will be a pretty basic example to get you started. You can accomplish this in a few different ways, but the most educational seemed to be an introduction to custom inspectors. Create a script called PrimativeSpawner, paste this in:
using UnityEngine;
using System.Collections;
using UnityEditor;
public class PrimativeSpawner : MonoBehaviour {
// Active primative choice
public UnityEngine.PrimitiveType primativeChoice;
// Spawn a primative based on the enum choice
public void CreateChosenPrimative()
{
// Check what's currently active
GameObject newPrimative = GameObject.CreatePrimitive(primativeChoice);
// Print the new thing's name
Debug.LogFormat("New Primative created! {0}", newPrimative.name);
}
}
// We can use a custom inspector for this
[CustomEditor(typeof(PrimativeSpawner))]
public class PrimativeSpawnerInspector : Editor
{
// Keep track of our current object being inspected
public PrimativeSpawner spawner;
// Replace the given inspector gui
public override void OnInspectorGUI()
{
// Draw the given inspector
this.DrawDefaultInspector();
// Check that it's been initialized
if (spawner == null)
spawner = this.serializedObject.targetObject as PrimativeSpawner;
// Simple Button
if (GUILayout.Button("Spawn Primative"))
spawner.CreateChosenPrimative();
}
}
You'll be able to choose a prefab then create it with a button click in its inspector:
Awesome! Thanks TreyH. I needed to change the Debug.LogFormat state to just a Debug.Log ins$$anonymous$$d, but other than that this worked for me. I should be able to figure it out from what you've provided. $$anonymous$$arking as Accepted.