unity-atoms/docs/tutorials/events.md
Miika Lönnqvist c7136d2937
Updated documentation and tutorials (#267)
Some tutorials now have animation in them to give a clearer explanation of how things work. Added a short tutorial about creating Atoms with the new Search function. Documentation about installation has also changed.
2021-06-14 20:32:52 +02:00

2.0 KiB
Raw Blame History

id title hide_title sidebar_label
events Events true Events

Events

Events are things that happens in our game that other scripts or entities could listen and subscribe to. Events are (like Variables) also Scriptable Objects that live outside of a specific scene. In Unity Atoms Events can be of different types and thereby pass along data to listeners. Variables do by default have the possibility to raise two specific Events:

  • Changed — raised every time a Variables value is changed. The Event contains the new value.
  • Changed With History — also raised every time a Variables value is changed. However, this Event contains both the new and the old value.

This makes it easier to make our game more data driven than just using Variables. Lets take a look at how that looks in our last example. We can create a new IntEvent and called HealthChangedEvent. Drop it on our IntVariable for the players health like this:

health-changed-event-drop

We can then modify our HealthBar.cs script to look like this:

using UnityEngine;
using UnityEngine.UI;
using UnityAtoms.BaseAtoms;

public class HealthBar : MonoBehaviour
{
    [SerializeField]
    private IntEvent HealthChangedEvent;
    [SerializeField]
    private IntConstant MaxHealth;

    void Start()
    {
        HealthChangedEvent.Register(this.ChangeFillAmount);
    }

    void OnDestroy()
    {
        HealthChangedEvent.Unregister(this.ChangeFillAmount);
    }

    private void ChangeFillAmount(int health)
    {
        GetComponent<Image>().fillAmount = 1.0f * health / MaxHealth.Value;
    }
}

And then inject the HealthChangedEvent to our HealthBar component:

events-to-healthbar

We now react to global state changes instead of checking the Variable value each Update tick. In other words we only update our Image component when we actually need to. That is pretty sweet!