Answers for "unity events"

C#
1

unityevent

using UnityEngine.Events;

// UnityEvents can also be serialized to the inspector
public class Foo : MonoBehaviour {
  UnityEvent action;
  
  void Start() {
    action = new UnityEvent();
    action.AddListener(() => { Debug.Log("Hello world!"); });
  }
  
  void Update() {
    action.Invoke();
  }
}
Posted by: Guest on August-28-2020
0

unity events

//Unity Events are great tools to create an easy workflow.
//If your callback functions require parameters, things are a little different.

//you can also try using delegates for this. (search: unity delegate)

//Class that contains the unity event (Owner Script)
using UnityEngine;
using UnityEngine.Events;

public class MyClass: MonoBehaviour
{
    public UnityEvent<Params> MyEvent;
	
    void Update()
    {
        if (condition)
        {
        	//Calls all of the 
            MyEvent.Invoke(params);
        }
    }
}

//Class that adds a listener (Listener Script)
public class MyListener: MonoBehaviour
{
	//You can also do this by assigning in the inspector
    //Don't use the inspector to connect functions with parameters
    public MyClass myClass;
	void Start()
    {
    	if(myClass == null) throw System.Exception("Can't assign listener to null.");
        myClass.MyEvent.AddListener(CallBack);
    }
    
    //Called when the owner script invokes the UnityEvent with the supplied parameters.
    void CallBack(params)
    {
    	Debug.Log("Callback called!");
    }
}
Posted by: Guest on September-20-2021

C# Answers by Framework

Browse Popular Code Answers by Language