Custom inspector. if bool is true then show variable
Asked Answered
I

3

0

I need editor script to drag GameObject and InputField in Inspector if and only if bool is true. If bool is false then don’t show InputField and GameObject field in Inspector. If true show that field in Inspector.

public bool StartTemp;
if( StartTemp )
{        
    public InputField iField;        // if StartTemp is true then only show in inspector.
    public GameObject Template;  // if StartTemp is true then only show in inspector.
}

If StartTemp is true then show InputField and GameObject field in Inspector.

GUILayout.BeginHorizontal();
GUILayout.Label("Team", GUILayout.Width(122));
_gmCtrl.teamMatch = EditorGUILayout.Toggle(_gmCtrl.teamMatch);
GUILayout.EndHorizontal();
if (_gmCtrl.teamMatch)
{
	GUILayout.Space(5);
	GUILayout.BeginHorizontal();
	GUILayout.Label("Friend", GUILayout.Width(122));
	_gmCtrl.noOfFriend = EditorGUILayout.IntField(_gmCtrl.noOfFriend);
	GUILayout.EndHorizontal();
	GUILayout.BeginHorizontal();
	GUILayout.Label("Enemy", GUILayout.Width(122));
	_gmCtrl.noOfEnemy = EditorGUILayout.IntField(_gmCtrl.noOfEnemy);
	GUILayout.EndHorizontal();
}

Just like this.

Bool false
84004-12.jpg
Bool true
84005-13.jpg

Impanation answered 9/10, 2023 at 7:45 Comment(2)

What is the question? Your code syntax is wrong, can you qualify your question for us please.

Savor

Any One? Is that possible ?

Impanation
R
0

RandomScript.cs

using UnityEngine;
using UnityEngine.UI;

#if UNITY_EDITOR
using UnityEditor;
#endif

public class RandomScript : MonoBehaviour
{
	[HideInInspector] // HideInInspector makes sure the default inspector won't show these fields.
	public bool StartTemp;

	[HideInInspector]
    public InputField iField;

	[HideInInspector]
	public GameObject Template;

	// ... Update(), Awake(), etc
}

#if UNITY_EDITOR
[CustomEditor(typeof(RandomScript))]
public class RandomScript_Editor : Editor
{
	public override void OnInspectorGUI()
	{
		DrawDefaultInspector(); // for other non-HideInInspector fields

		RandomScript script = (RandomScript)target;

		// draw checkbox for the bool
		script.StartTemp = EditorGUILayout.Toggle("Start Temp", script.StartTemp);
		if (script.StartTemp) // if bool is true, show other fields
		{
			script.iField = EditorGUILayout.ObjectField("I Field", script.iField, typeof(InputField), true) as InputField;
			script.Template = EditorGUILayout.ObjectField("Template", script.Template, typeof(GameObject), true) as GameObject;
		}
	}
}
#endif
Recrement answered 6/6, 2023 at 2:31 Comment(2)

Cresspresso - Why hide the initiating bool (StartTemp) in the main Class (lines 10 & 11) and then force the show in the Editor Script (lines 32 & 33)? It works with the initiating bool shown in the default CS Class (pulling the "[HideInInspector]" from line 10) and commenting out line 33. Am I missing something? (And I realize I'm 5-years late to this party AND YOUR answer is still perfect! (in Unity 2019.2.7f2) I'm just trying to understand if it is a preference (explicitly hiding & showing stuff) or a Unity requirement that became moot along the way...

Feliciafeliciano

Thoses variables that are displayed reset to null when launching the game :/ Do you know why and if I can change this ? I hop you still use this account lol :p

Stevie
J
0

Just put the drawing of those fields inside the “if”

_gmCtrl.teamMatch = EditorGUILayout.Toggle(_gmCtrl.teamMatch);
if (_gmCtrl.teamMatch) {
    var gameObject = EditorGUILayout.ObjectField(source, typeof(GameObject), true);
)
Janice answered 6/6, 2023 at 2:0 Comment(1)

Thanks @Janice . I will try this. Do you know about InputField?

Impanation
R
0

RandomScript.cs

using UnityEngine;
using UnityEngine.UI;

#if UNITY_EDITOR
using UnityEditor;
#endif

public class RandomScript : MonoBehaviour
{
	[HideInInspector] // HideInInspector makes sure the default inspector won't show these fields.
	public bool StartTemp;

	[HideInInspector]
    public InputField iField;

	[HideInInspector]
	public GameObject Template;

	// ... Update(), Awake(), etc
}

#if UNITY_EDITOR
[CustomEditor(typeof(RandomScript))]
public class RandomScript_Editor : Editor
{
	public override void OnInspectorGUI()
	{
		DrawDefaultInspector(); // for other non-HideInInspector fields

		RandomScript script = (RandomScript)target;

		// draw checkbox for the bool
		script.StartTemp = EditorGUILayout.Toggle("Start Temp", script.StartTemp);
		if (script.StartTemp) // if bool is true, show other fields
		{
			script.iField = EditorGUILayout.ObjectField("I Field", script.iField, typeof(InputField), true) as InputField;
			script.Template = EditorGUILayout.ObjectField("Template", script.Template, typeof(GameObject), true) as GameObject;
		}
	}
}
#endif
Recrement answered 6/6, 2023 at 2:31 Comment(2)

Cresspresso - Why hide the initiating bool (StartTemp) in the main Class (lines 10 & 11) and then force the show in the Editor Script (lines 32 & 33)? It works with the initiating bool shown in the default CS Class (pulling the "[HideInInspector]" from line 10) and commenting out line 33. Am I missing something? (And I realize I'm 5-years late to this party AND YOUR answer is still perfect! (in Unity 2019.2.7f2) I'm just trying to understand if it is a preference (explicitly hiding & showing stuff) or a Unity requirement that became moot along the way...

Feliciafeliciano

Thoses variables that are displayed reset to null when launching the game :/ Do you know why and if I can change this ? I hop you still use this account lol :p

Stevie
E
0

i did this attribute, i hope work in your proyect

/* Title : Attribute for show a field if other field is true or false.
 * Author : Anth
*/
using UnityEngine;
using UnityEditor;

/// <summary>
/// Atttribute for show a field if other field is true or false.
/// </summary>
[System.AttributeUsage(System.AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public sealed class ShowIfAttribute : PropertyAttribute
{
    public string ConditionalSourceField;
    public bool expectedValue;
    public bool HideInInspector;

    /// <summary>
    /// Create the attribute for show a field x if field y is true or false.
    /// </summary>
    /// <param name="ConditionalSourceField">name of field y type boolean </param>
    /// <param name="expectedValue"> what value should have the field y for show the field x</param>
    /// <param name="HideInInspector"> if should hide in the inspector or only disable</param>
    public ShowIfAttribute(string ConditionalSourceField, bool expectedValue, bool HideInInspector = false)
    {
        this.ConditionalSourceField = ConditionalSourceField;
        this.expectedValue = expectedValue;
        this.HideInInspector = HideInInspector;
    }
}


[CustomPropertyDrawer(typeof(ShowIfAttribute))]
public class ConditionalHidePropertyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
#if UNITY_EDITOR
        ShowIfAttribute condHAtt = (ShowIfAttribute)attribute;
        bool enabled = GetConditionalSourceField(property, condHAtt);
        GUI.enabled = enabled;

        // if is enable draw the label
        if (enabled)
            EditorGUI.PropertyField(position, property, label, true);
        // if is not enabled but we want not hide it, then draw it disabled
        else if (!condHAtt.HideInInspector)
            EditorGUI.PropertyField(position, property, label, false);
        // else hide it ,dont draw it
        else return;
#endif
    }

    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
#if UNITY_EDITOR
        ShowIfAttribute condHAtt = (ShowIfAttribute)attribute;
        bool enabled = GetConditionalSourceField(property, condHAtt);

        // if is enable draw the label
        if (enabled)
        {
            return EditorGUI.GetPropertyHeight(property, label, true);
        }
        // if is not enabled but we want not hide it, then draw it disabled
        else
        {
            if (!condHAtt.HideInInspector)
                return EditorGUI.GetPropertyHeight(property, label, false);
            // else hide it
            else
                return -EditorGUIUtility.standardVerticalSpacing; // Oculta el campo visualmente.
        }
#else
        return 0f;
#endif
    }

    /// <summary>
    /// Get if the conditional what expected is true.
    /// </summary>
    /// <param name="property"> is used for get the value of the property and check if return enable true or false </param>
    /// <param name="condHAtt"> is the attribute what contains the values what we need </param>
    /// <returns> only if the field y is same to the value expected return true</returns>
    private bool GetConditionalSourceField(SerializedProperty property, ShowIfAttribute condHAtt)
    {
#if UNITY_EDITOR
        bool enabled = false;
        string propertyPath = property.propertyPath;
        string conditionPath = propertyPath.Replace(property.name, condHAtt.ConditionalSourceField);
        SerializedProperty sourcePropertyValue = property.serializedObject.FindProperty(conditionPath);

        if (sourcePropertyValue != null)
        {
            enabled = sourcePropertyValue.boolValue;
            if (enabled == condHAtt.expectedValue) enabled = true;
            else enabled = false;
        }
        else
        {
            string warning = "ConditionalHideAttribute: No se encuentra el campo booleano [" + condHAtt.ConditionalSourceField + "] en " + property.propertyPath;
            warning += " Asegúrate de especificar correctamente el nombre del campo condicional.";
            Debug.LogWarning(warning);
        }

        return enabled;
#else
        return false;
#endif
    }
}

example how use:

    [SerializeField] bool isOneShot = false;
    // Audio no oneShot Options
    [ShowIf("isOneShot", false)][SerializeField] float timeStart = 0f;
    [Tooltip("If active this, every time the sound player play begin from the timeStart")]
    [ShowIf("isOneShot", false)][SerializeField] bool keepTimeStart = true;

this if the field oneshot is false the other fields are active
but when active the field one shot the other fields are desactived the two forms
first form is disable

two form is hide in inspector for this need set other value in the ShowIf

    [SerializeField] bool isOneShot = false;
    // Audio no oneShot Options
    [ShowIf("isOneShot", false,true)][SerializeField] float timeStart = 0f;
    [Tooltip("If active this, every time the sound player play begin from the timeStart")]
    [ShowIf("isOneShot", false,true)][SerializeField] bool keepTimeStart = true;

now when desactived the fields hide in the inspector

Eldest answered 18/1 at 22:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.