【问题标题】:Instantiate class and set properties from the editor view Unity C#从编辑器视图 Unity C# 实例化类并设置属性
【发布时间】:2016-07-03 12:28:19
【问题描述】:

我有以下课程:

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

以及包含该类的类:

public class SpellDamage : MonoBehaviour
{
    public BaseDamage SpellBaseDamage;
}

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

我该怎么做?

【问题讨论】:

  • 我不确定这是否可行,但如果可以,很可能需要一些自定义编辑器脚本。还有一种选择是让SpellDamage 继承自BaseDamage(顺便说一下,该类不需要Serializable)。
  • 即使它继承了我在另一个类中仍然有SpellDamage 类,所以仍然不可能从编辑器中实例化它
  • 在这种情况下,您应该记住,unity 是一个基于组件的系统。使Damage 类成为一个组件(只需将其附加到相应的游戏对象(例如玩家)并设置值)并让其他脚本引用该组件。
  • 此外,您始终可以将值传递给一个类,例如Start.
  • 永远,永远使用“Serializable”。作为一个好奇心,你甚至在哪里看到的?删除它。

标签: c# class unity3d editor instance


【解决方案1】:

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

您已添加 Serializable 属性。您需要做的是在 Editor 文件夹中为 BaseDamage 类编写一个 Custom Property 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-25
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    相关资源
    最近更新 更多