我创建了一个自定义编辑器,其中自动添加了对象及其组件。
但是如何通过脚本在UnityEvent
中放置Unity组件内置函数?
在这种情况下,我想将音频源Play()
功能放在UnityEvent
脚本中。
答案 0 :(得分:3)
希望这有效:
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 events;
UnityAction methodDelegate;
bool eventAdded = false;
void OnEnable(){
UpdateInspector ();
}
void UpdateInspector(){
if (!eventAdded) {
audioSrc = GetComponent<AudioSource> ();
events = new UnityEvent ();
methodDelegate = System.Delegate.CreateDelegate (typeof(UnityAction), audioSrc, "Play") as UnityAction;
UnityEditor.Events.UnityEventTools.AddPersistentListener (events, methodDelegate);
eventAdded = true;
}
}
}
答案 1 :(得分:1)
您可以使用unityEvent.AddListener
public class EventRunner : MonoBehaviour {
public AudioSource audioSource;
public UnityEvent ev;
IEnumerator Start () {
//you won't see an entry comes up in the inspector
ev.AddListener(audioSource.Play);
while (true)
{
ev.Invoke(); //you will hear the sound
yield return new WaitForSeconds(0.5f);
}
}
}
答案 2 :(得分:1)
感谢@zayedupal,这是自动创建游戏对象,对象组件并自动在编辑器中添加UnityEvent的完整答案。
[MenuItem("GameObject/Create Animation/With SFX", false, -1)]
static void CreateAnimationWithSFX()
{
GameObject go = new GameObject("animationWithSFX");
go.transform.SetParent(Selection.activeTransform);
AudioSource audioSource = go.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
// Automate-add the right channel for audio source
AudioMixer mixer = Resources.Load("Master") as AudioMixer;
audioSource.outputAudioMixerGroup = mixer.FindMatchingGroups("SFX")[0];
SceneAnimationEvent script = go.AddComponent<SceneAnimationEvent>();
// Automate-add the unity built-in function into UnityEvent
script.Events = new UnityEvent ();
UnityAction methodDelegate = System.Delegate.CreateDelegate (typeof(UnityAction), audioSource, "Play") as UnityAction;
UnityEventTools.AddPersistentListener (script.Events, methodDelegate);
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
Selection.activeObject = go;
}