How to dynamically switch between public and private variables in Unity

Viewed 767

I wrote the following script in Unity C#.

Test.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{

    public bool showParams = true;
    public int test1 = 100;
    public string test = "";
    
    // Use this for initialization
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {

    }
}

I want to switch whether other parameters are displayed in the Inspector by turning on/off the showParams variable.

As shown in the image below, when showParams is ON, all variables are public. enter image description here

As shown in the image below, I want to prevent all variables from being displayed when showParams is OFF.

enter image description here

I want to switch whether other parameters are displayed in the Inspector by turning on/off the showParams variable.

As shown in the image below, when showParams is ON, all variables are public.

As shown in the image below, I want to prevent all variables from being displayed when showParams is OFF.

Is this possible with Unity C#?

2 Answers

You'll need to write a custom editor for your class to be able to do this. You cannot change the access modifiers (public and private) of the members of your class after the code has compiled, which needs to happen for them to show up in the inspector.

See the docs for how to write a custom editor.

As others have pointed out this option is not built into Unity. You will have to write your own custom inspector or property drawer.

Luckily there are many people that faced this same issue before you so there are multiple Unity editor extensions over the internet that do this. You can search Google or Github for "unity conditional hide" to find them. The one I personally found usefull is https://github.com/krishx007/ConditionalHideAttribute_Unity

Related