Select only one Layer in the inspector,Select only one layer in the inspector
Hi!
I have a monster that normally is hidden, but when it gets revealed it has to change his layer to another one, defined in the inspector. Right now I have this:
[SerializeField]
private LayerMask revealedLayerMask;
private LayerMask RevealedLayerMask => (int) Math.Log(revealedLayerMask, 2);
This works fine; the problem is that the default LayerMask field in the Inspector allows me to select more than one Layer, and if that happens, the RevealedLayerMask function will return a weird result.
I would like to select only one Layer, so it doesn't have the multiple layers problem, and maybe it gives an int and not a bitmask so I can avoid using Log to get the int.
I know I could just input text but that is not what I want.
Is there a way to do this? Thanks
Answer by FatRedBird · Feb 05, 2021 at 07:43 AM
Found the answer to this here:
https://answers.unity.com/questions/609385/type-for-layer-selection.html
(pasting it incase that link gets broken)
Answer by Kyle_WG · Oct 29, 2014 at 03:19 PM
An answer to an old post but I created a wrapper in C# for this issue cause I was tired of not being able to have one simple layer select or just using an integer.
For anyone else who stumbles on the message and issue. (heh) Always reminds me of this xkcd comic link text
Here's the wrapper class:
using UnityEngine;
[System.Serializable]
public class SingleUnityLayer
{
[SerializeField]
private int m_LayerIndex = 0;
public int LayerIndex
{
get { return m_LayerIndex; }
}
public void Set(int _layerIndex)
{
if (_layerIndex > 0 && _layerIndex < 32)
{
m_LayerIndex = _layerIndex;
}
}
public int Mask
{
get { return 1 << m_LayerIndex; }
}
}
And here's the PropertyDrawer class. (Remember to throw it in a Editor folder in project.)
using UnityEditor;
using UnityEngine;
[CustomPropertyDrawer(typeof(SingleUnityLayer))]
public class SingleUnityLayerPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
{
EditorGUI.BeginProperty(_position, GUIContent.none, _property);
SerializedProperty layerIndex = _property.FindPropertyRelative("m_LayerIndex");
_position = EditorGUI.PrefixLabel(_position, GUIUtility.GetControlID(FocusType.Passive), _label);
if (layerIndex != null)
{
layerIndex.intValue = EditorGUI.LayerField(_position, layerIndex.intValue);
}
EditorGUI.EndProperty( );
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612222136im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Scriptable Object issues when inside .dll 1 Answer
Public fields not showing in inspector 1 Answer
Destroy gameobjects several times in a scene. Also destroy other instances of that gameobject. 2 Answers
Values not updating in Unity. - UPDATED 1 Answer
How to add a editing option to variables in a script in Inspector? 0 Answers