如何使用脚本在UnityEvent中添加Unity组件功能

Ten*_*lah 1 c# unity-game-engine

我创建了一个自定义编辑器,其中会自动添加对象及其组件。

但是如何将Unity组件内置函数放入UnityEventvia脚本中呢?

在这种情况下,我想将音频源Play()函数放在UnityEventvia脚本中。

前 后

小智 6

希望这有效:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;

[ExecuteInEditMode]
[RequireComponent (typeof (AudioSource))]
public class SceneAnimationEvent : MonoBehaviour {
    public AudioSource audioSrc;
    [SerializeField]
    public UnityEvent unityEvent;
    UnityAction methodDelegate;
    bool eventAdded = false;

    void OnEnable() {
        UpdateInspector ();
    }
    void UpdateInspector() {
        if (!eventAdded) {
            audioSrc = GetComponent<AudioSource> ();
            unityEvent = new UnityEvent ();
            methodDelegate = System.Delegate.CreateDelegate (typeof(UnityAction), audioSrc, "Play") as UnityAction;
            UnityEditor.Events.UnityEventTools.AddPersistentListener (unityEvent, methodDelegate);
            eventAdded = true;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)