Simple event system in Unity

I am trying to use the event system in Unity (C # path), but I am having problems with its implementation.

Most examples show one class in which you define a handler; then you write in the same class, a function that matches the signature of the handler, and you write events as static

public class EventExample : MonoBehaviour
{
    public delegate void ExampleEventHandler();
    public static event ExampleEventHandler OneDayPassed;

    public static void NextTurn()
    {
        // do stuff then send event
        if (OneDayPassed != null)
            OneDayPassed();
    }
}

Then in another class, you subscribe to events, creating a function that actually does something

public class EntityWatcher: MonoBehaviour
{
    void Start()
    {
        EventExample.OneDayPassed += this.PrepareNextDay;
    }

    public void PrepareNextDay()
    {
        // Do other stuff that happen after the day is done

    }
}

, , , GameObject . , GO, 8 6, ; , script, Game Object, ?

, , 8 6 , , "", , .

, script , , , .

+5
2

UnityEvent.

    public UnityEvent whoa;

.

BigScript.cs

using UnityEngine;
using System.Collections;
using UnityEngine.Events;

public class BigScript:MonoBehaviour
    {
    [Header("Here a cool event! Drag anything here!")]
    public UnityEvent whoa;
    }

. .

"".

, - , "".

enter image description here

. BigScript,

public class BigScript:MonoBehaviour
    {
    [Header("Here a cool event! Drag anything here!")]
    public UnityEvent whoa;

    private void YourFunction()
      {
      whoa.Invoke();
      }

( : if (whoa!=null) whoa.Invoke();)


, . :

whoa.AddListener(ScreenMaybeChanged);

( , - , . .)


, .

. *


, , .

:

, ONE FLOAT:

:

[System.Serializable] public class _UnityEventFloat:UnityEvent<float> {}

. .

...
using UnityEngine.Events;

// magic line of code...
[System.Serializable] public class _UnityEventFloat:UnityEvent<float> {}

public class SomeThingHappens : MonoBehaviour
{
    public _UnityEventFloat changedLength;
    public _UnityEventFloat changedHeight;

    ... and then ... 

    void ProcessValues(float v)
    {
        ....
        if (changedLength != null) changedLength.Invoke(1.4455f);
    }
}

:

, - " ".

enter image description here

" "!

Unity!

+21

, . , , , . : .

: .

+1

Source: https://habr.com/ru/post/1627429/


All Articles