How to hide variables depending on other variables

2019-08-18 17:25发布

问题:

how do i hide variables depending on other variables values in the unity inspector. Basically imagine this: if i had a bool called "CanSprint" and a float "SprintSpeed" so i want to make it so that when the bool is true, the float is showing, but when the bool is false, the float hides. This is just to be a little bit neater. Thanks!

回答1:

You need to look into custom editor scripts (https://docs.unity3d.com/Manual/editor-CustomEditors.html), using a custom editor script you can show variables whenever you like. Here's a layout using the information from the links:

[CustomEditor(typeof(MyBehaviourClass))]
public class MyEditorClass : Editor
{
    public override void OnInspectorGUI()
    {
        // If we call base the default inspector will get drawn too.
        // Remove this line if you don't want that to happen.
        base.OnInspectorGUI();

        MyBehaviourClass myBehaviour = target as MyBehaviourClass;

        target.myBool = EditorGUILayout.Toggle("myBool", target.myBool);

        if (target.myBool)
        {
            target.someFloat = EditorGUILayout.FloatField ("Some Float:", target.someFloat);

        }
    }
}

Be sure to stick this script in the 'Editor' folder, change 'MyBehaviourClass' to your class type, change 'someFloat' to your float and 'myBool' to your boolean variable.