Reputation: 45
How can i code so people can't add/remove list elements from the inspector, but still be able to see the elements?
Something like
[ReadOnlyField, NonReorderable]public List<CustomType> CustomTypeList = new();
Upvotes: 1
Views: 1016
Reputation: 26
You can use custom editor for this, here is an example
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class Example : MonoBehaviour
{
[System.Serializable]
public class Item
{
public int a;
public string b;
public Vector2 v;
}
public List<Item> listArrayA = new() { new Item(), new Item() };
public List<Item> listArrayB = new() { new Item(), new Item() };
public Item itemA;
#if UNITY_EDITOR
[CustomEditor(typeof(Example))]
public class ExampleEditor : Editor
{
private string[] disableProperties = new string[] { "listArrayB", "itemA" };
public override void OnInspectorGUI()
{
DrawPropertiesExcluding(serializedObject, this.disableProperties);
EditorGUI.BeginDisabledGroup(true);
for (var i = 0; i < this.disableProperties.Length; i++)
{
EditorGUILayout.PropertyField(serializedObject.FindProperty(this.disableProperties[i]));
}
EditorGUI.EndDisabledGroup();
serializedObject.ApplyModifiedProperties();
}
}
#endif
}
Result
If you just want to prevent other editing your fields, no need to create custom editor, just make theme private fields then create public properties to access theme, their values can be viewed by change Inspector mode to Debug Change inspector view mode to debug
Upvotes: 1
Reputation: 4049
Sure, you could hack a solution with OnValidate as described here. The general flow would be to read the list of items when the object is enabled and store those in a secondary array. When OnValidate is called, if the list visible in the Inspector doesn’t match the peivate list, then overwrite the elements in the visible list with the private items. Note, you can’t just assign one List object to another. This won’t copy a list, it’ll just make both variables point to the same list. So, the answer is yes, it can be done.
Now, ask me if this is a good idea. The answer would be, no, I don’t see any good reason for this. If you’re worried about a designer, for example, mucking up your list of items, then either move those items elsewhere the designer is told not to touch, hard code the items, or instantiate them if need be.
Upvotes: 1
Reputation: 828
It's not possible. Maybe you can try creating a custom editor script just to show them in the inspector.
Upvotes: 0