Search Unity

Setting UnityEvent default function?

Discussion in 'Scripting' started by Noktai, Oct 6, 2015.

  1. Noktai

    Noktai

    Joined:
    Feb 11, 2013
    Posts:
    40
    I'm trying to setup a structure where a UnityEvent should have a default function.

    UnityEvent doesn't seem to have a constructor so I cannot attach a delegate in the field declaration.

    Right now I'm trying this;
    Code (CSharp):
    1.  
    2.   public UnityEvent sleepEvent;
    3.     protected void Start()
    4.     {
    5.          sleepEvent.AddListener( new UnityAction( () => { OnSetSleep(); } ) );
    6.     }
    with ExecuteInEditMode to make it work in the editor. But it doesn't seem to do anything.
    Any help?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    6,525
    I don't believe that Start() is ever executed in edit mode, even with the attribute. You may want to put it in a context menu-triggered function instead.
     
  3. BenZed

    BenZed

    Joined:
    May 29, 2014
    Posts:
    524
    Start (and Awake) is executed in edit mode when you first place the component onto the object (or when you first load the scene)

    AddListener adds a non-persistent listener to the UnityEvent, which do not show up in the editor and are not serialized. This only works at runtime.

    The ones that show up in the editor are Persistent listeners. You can only add and remove them through the inspector, or using the UnityEditor namespace. Calling RemoveAllListeners at runtime only removes non-persistent listeners.

    To add Persistent Listeners via scripting, use the UnityEventTools static class:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Events;
    3. using UnityEditor.Events;
    4.  
    5. [ExecuteInEditMode]
    6. public class Foo : MonoBehaviour {
    7.  
    8.     [SerializeField]
    9.     UnityEvent serializedEvent;
    10.  
    11.     void Awake()
    12.     {
    13.         //So that it only creates the listener once, when the component is dragged on, not when the scene is loaded.
    14.         if (serializedEvent == null) {
    15.             serializedEvent = new UnityEvent ();
    16.             UnityEventTools.AddVoidPersistentListener (serializedEvent, Bar);
    17.         }
    18.     }
    19.  
    20.     void Start()
    21.     {
    22.         serializedEvent.Invoke ();
    23.     }
    24.  
    25.     public void Bar()
    26.     {
    27.         Debug.Log ("Bar Called.");
    28.     }
    29. }
    30.  
     
    fogsight and StarManta like this.