从定制编辑器传递UnityEvent到对象

时间:2019-08-17 17:50:30

标签: c# unity3d serialization

是否可以从自定义检查器获取UnityEvent数据并将其传递给另一个对象?

我有以下课程:

public class PointOfInterestCreator : MonoBehaviour
{
    public string poiName;
    public Sprite poiSprite;
    public Vector3 poiPosition;
    public Vector3 poiRotation;
    public UnityEvent OnClickEvent;
}

为此,我制作了一个自定义检查器,可让您从编辑器创建兴趣点。

[CustomEditor(typeof(PointOfInterestCreator))]
public class PointOfInterestBuilder : Editor
{
    private SerializedProperty pointOfInterestName;
    //...
    private SerializedProperty pointOfInterestOnClickEvent;

    private void OnEnable()
    {
        pointOfInterestName = serializedObject.FindProperty("poiName");
        //...
        pointOfInterestOnClickEvent = serializedObject.FindProperty("OnClickEvent");
    }

    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        EditorGUILayout.PropertyField(pointOfInterestName);
        //..
        EditorGUILayout.PropertyField(pointOfInterestOnClickEvent);

        currentPOI.name = pointOfInterestName.stringValue;
        //..
        UnityEvent myEvent = (UnityEvent)pointOfInterestOnClickEvent.objectReferenceValue;//This errors
}

此自定义检查器的外观符合预期,并显示UnityEvent的字段,并允许我添加单位事件。

The custom inspector

现在,当我单击“兴趣点”按钮时,我将实例化并使用设置其值

poi.SetValues(currentPOI.name, currentImage.sprite, currentPOI.transform.localPosition, currentPOI.transform.localRotation.eulerAngles myEvent);

调用以下方法。

public void SetValues(string name, Sprite sprite, Vector3 position, Vector3 rotation, UnityEvent onClick)
{
    poiName = name;
    poiPosition = position;
    poiSprite = sprite;
    poiRotation = rotation;
    OnClickEvent = onClick;
}

这对于除UnityEvent之外的所有值都适用。返回错误error CS0030: Cannot convert type 'UnityEngine.Object' to 'UnityEngine.Events.UnityEvent'

我尝试使用UnityEventSerializedProperty获取UnityEvent myEvent = (UnityEvent)pointOfInterestOnClickEvent.objectReferenceValue;数据的行上发生此错误

我尝试了SerializedProperty公开的所有其他值类型,但没有一个允许我将其强制转换/存储为UnityEvent。有办法吗?

我也尝试过

UnityEvent myEvent = (UnityEvent)pointOfInterestOnClickEvent.FindPropertyRelative("OnClickEvent");

返回错误error CS0030: Cannot convert type 'UnityEditor.SerializedProperty' to 'UnityEngine.Events.UnityEvent'

0 个答案:

没有答案