实例化 class 并从编辑器视图 Unity C# 中设置属性

Instantiate class and set properties from the editor view Unity C#

我有以下 class :

[Serializable]
public class BaseDamage : MonoBehaviour
{
    public int MaximumDamage;
    public int MinimumDamage;
    public short SpellScaling;
}

和一个 class 其中包含 class :

public class SpellDamage : MonoBehaviour
{
    public BaseDamage SpellBaseDamage;
}

当我将 SpellDamage 脚本附加到游戏对象时,我希望能够从编辑器视图中设置 BaseDamage 的值,但它只允许我将脚本附加到它。

我该怎么做?

你走在正确的轨道上。您可以将 BaseDamage 脚本附加到与 SpellDamage 脚本附加到的同一游戏对象。

您已添加 Serializable 属性。您需要做的是在 Editor 文件夹中为 BaseDamage class 写一个 Custom 属性 Drawer

像这样:

[CustomPropertyDrawer(typeof(BaseDamage))]
public class BaseDamageDrawer : PropertyDrawer
{


static string[] propNames = new[]
{
    "MaximumDamage",
    "MinimumDamage",
    "SpellScaling",
};



public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
    // Using BeginProperty / EndProperty on the parent property means that
    // prefab override logic works on the entire property.
    EditorGUI.BeginProperty(position, label, property);

    // Draw label
    position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);

    // Don't make child fields be indented
    var indent = EditorGUI.indentLevel;
    EditorGUI.indentLevel = 0;

    SerializedProperty[] props = new SerializedProperty[propNames.Length];
    for (int i = 0; i < props.Length; i++)
    {
        props[i] = property.FindPropertyRelative(propNames[i]);
    }


    // Calculate rects
    float x = position.x;
    float y = position.y;
    float w = position.width / props.Length;
    float h = position.height;
    for (int i = 0; i < props.Length; i++)
    {
        var rect = new Rect(x, y, w, h);
        EditorGUI.PropertyField(rect, props[i], GUIContent.none);
        x += position.width / props.Length;
    }

    // Set indent back to what it was
    EditorGUI.indentLevel = indent;

    EditorGUI.EndProperty();
}