我怎样才能在脚本顶部禁用变量,同时在代码的其余部分使用它们?

How can i disable variables in the top of script but also use them in the rest of the code?

public List<string> dialogueLines = new List<string>();
public string npcName;

我想在 Inspector 中看到它们,因为稍后在脚本中我给这个变量赋值,但我不希望用户在游戏 [=13] 时能够更改 Inspector 中的值=].我不想将它们隐藏在检查器中只是为了让用户无法更改它们。

您希望您的变量只能通过编辑器读取。可以在 Unity 论坛上找到与您要查找的内容接近的 CustomPropertyDrawer which can be used to make a custom Editor attribute. An example

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


public class ReadOnlyAttribute : PropertyAttribute
{

}

[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : PropertyDrawer
{
    public override float GetPropertyHeight(SerializedProperty property,
                                            GUIContent label)
    {
        return EditorGUI.GetPropertyHeight(property, label, true);
    }

    public override void OnGUI(Rect position,
                               SerializedProperty property,
                               GUIContent label)
    {
        GUI.enabled = false;
        EditorGUI.PropertyField(position, property, label, true);
        GUI.enabled = true;
    }
}

测试:

您可以使用 ReadOnly 属性使其成为只读变量。

public class Test : MonoBehaviour
{
    [ReadOnly]
    public List<string> dialogueLines;

    [ReadOnly]
    public string npcName;
}

效果很好。唯一的问题是使用List/Array时,size仍然可以改变,但是List/Array中的item/element不能改变。