2017-08-09 4 views
0

オブジェクトとそのコンポーネントが自動的に追加されるカスタムエディタを作成しました。UnityEventのUnityコンポーネント関数をスクリプトを使って追加する方法

しかし、Unityコンポーネントの組み込み関数をスクリプトでUnityEventに入れるにはどうすればよいですか?

この場合、オーディオソースPlay()をスクリプトを介してUnityEventに入れたいと思います。

before after

答えて

2

を使用することができます。@zayedupalする

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; 
     } 
    } 
} 
+0

他の誰かが同じ問題に遭遇した場合、私はフルコードを掲載します。 –

0

あなたはこの作品を希望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); 
     } 

    } 
} 
+0

再生モードに入ることなく、リスナーをエディタに追加する必要があります。 –

0

おかげで、これは、ためのコンポーネントに自動的にゲームオブジェクトを作成するには、完全な答えでありますエディターに自動的に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; 
} 
関連する問題