- Home /
Adapt variables based on other variables... confusing
Simply, what I want to be able to do is this:
to be able to have other public variables depending on a variable
eg.
I have an enum with the types "normal" and "advanced"
public enum Type {normal, advanced};
then if, whether the variable is set in code or in the inspector, the enum "Type" is "normal" for me to have another variable called "height", for example, or if the Tpye is set to advanced for me to have the public variable "speed"
For clarity, to have something like this(before the start function):
public enum Type {normal, advanced};
public Type type;
if(type == Type.normal)
public int height;
else if(type == Type.advanced)
public int speed;
void Start()
{
//...
and for the inspector to look like this
or this
Any help or advice is greatly appreciated,
thanks in advance
Minchuilla
Answer by Chris_Dlala · May 29, 2014 at 09:23 PM
Hi, what you want is a Custom Inspector. These allow you to design exactly how the inspector should look and behave. They allow you to add most types of GUI controls with ease. I'll add a simple example for the behaviour you require:
enter code hereusing UnityEngine;
using System.Collections;
public class MyScript : MonoBehaviour
{
public enum MyTypes { TypeOne, TypeTwo }
public MyTypes myType;
public int Height { get; set; }
public int Width { get; set; }
}
Given this class/script, the default inspector will draw the public enum myType
but will not draw anything for Height and Width because they are Properties and Unity does not show properties in the inspector. I often do this so that my custom inspector has access to them but they are not drawn by default. Now here is a custom inspector for it:
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MyScript))]
public class MyScriptInspector : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
MyScript myScript = target as MyScript;
switch(myScript.myType)
{
case MyScript.MyTypes.TypeOne:
myScript.Height = EditorGUILayout.IntField("Height" ,myScript.Height);
break;
case MyScript.MyTypes.TypeTwo:
myScript.Width = EditorGUILayout.IntField("Width", myScript.Width);
break;
}
if (GUI.changed)
{
EditorUtility.SetDirty(target);
}
}
}
Most of the code here is pretty self explanatory. EditorGUILayout is your friend. Remember that the Editor script must be inside a folder called "Editor". I hope that helped =)
Thanks, that exactly what I was looking for and has helped me make a lot of things easier.
Your answer
![](https://koobas.hobune.stream/wayback/20220613150208im_/https://answers.unity.com/themes/thub/images/avi.jpg)