我創建了一個自定義編輯器,其中自動添加了對象及其組件。如何使用腳本在UnityEvent中添加Unity組件功能
但是我如何通過腳本在UnityEvent
中插入Unity組件內置函數?
在這種情況下,我想通過腳本將音頻源Play()
函數放在UnityEvent
中。
我創建了一個自定義編輯器,其中自動添加了對象及其組件。如何使用腳本在UnityEvent中添加Unity組件功能
但是我如何通過腳本在UnityEvent
中插入Unity組件內置函數?
在這種情況下,我想通過腳本將音頻源Play()
函數放在UnityEvent
中。
希望這個作品:
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;
}
}
}
您可以使用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);
}
}
}
我需要在編輯器中添加監聽器,而無需進入播放模式。 –
感謝@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;
}
它的工作,如果有人遇到同樣的問題,我會發布我的完整代碼。 –