C# Conditional Properties

Question 1:
I am trying to create a C# class that will be added to each object in my game. I wanted some of the properties to only show up in the inspector if the level designer has specified the main properties. For example: if the level designer ticked the box to “Effect Player” i want the properties related to that property to show up under it, such as “kill player”, “Telport Player” and so on. Otherwise they should be hidden from view, making the inspector panel less cluttered.

Is there a way to do this? If so, how?

Question 2:
Is it possible to do this with an array of objects? So that the level designer could select multiple objects/transforms and then modify there properties.

You could achieve that by writing your own custom editor.
http://unity3d.com/support/documentation/ScriptReference/Editor.html

For example, let’s say you have a script named Effects:

public enum PlayerEffect
{
    Kill,
    Teleport
}
public class Effects : MonoBehaviour
{
    public bool usePlayerEffects;
    public PlayerEffect playerEffect;
}

Then you can write this custom editor:

using UnityEditor;
[CustomEditor( typeof(Effects) )]
public class EffectsInspector : Editor
{
    public override void OnInspectorGUI()
    {
        Effects effects = target.GetComponent<Effects>();
        
        effects.usePlayerEffects = EditorGUILayout.Toggle("Use player effects", effects.usePlayerEffects);
        if (effects.usePlayerEffects)
        {
            effects.playerEffect = EditorGUILayout.EnumPopup("Player Effect", effects.playerEffect );
        }
    }
}

Try to play with all methods of EditorGUILayout to achieve your goal.

I found it!!

You put [System.Serializable] in front of the class and then put [HideInInspector] in front of every property. Eg:

public enum PlayerEffect{None, Kill, StopVelocity, ChangeVelocityMultiplier, Teleport}
[System.Serializable]
public class PlayerEffects
{
       //Hide property in inspector
        [HideInInspector]
        public bool usePlayerEffects;
        // Show propery in inspector
        public PlayerEffect playerEffect;
}

Here’s my Inspector Code:

using UnityEditor;

[CustomEditor( typeof(PlayerEffects) )]

public class PlayerEffectsEditor: Editor{

public override void OnInspectorGUI (){

     PlayerEffects effectPlayer = (PlayerEffects)target;
     effectPlayer.usePlayerEffects = EditorGUILayout.Toggle("Effect Player:", effectPlayer.usePlayerEffects);

        if (effectPlayer.usePlayerEffects){
            effectPlayer.playerEffect = (PlayerEffect)EditorGUILayout.EnumPopup("Effect",effectPlayer.playerEffect);	
        }
		base.OnInspectorGUI ();
	}
}

Thanks again! :slight_smile: