Skip to content

Scriptable Architecture

DucNV_2000 edited this page Feb 28, 2024 · 21 revisions

What

Scriptable Objects are an immensely powerful yet often underutilized feature of Unity. Learn how to get the most out of this versatile data structure and build more extensible systems and data patterns.

Introductory video about Game Architecture with Scriptable Objects

01-image-F-1020x574

Use

Scriptable Event

Create Scriptable Event

You can create Scriptable Event by 3 option

  • Option 1: via menu Create > Sunflower > Scriptable > Event

create_event1

  • Option 2: menu item Sunflower > Scriptable > Create Event

create_event2

  • Option 3: Open tab Scriptable Event in Sunflower Control Panel

create_event3

  • Scriptable Event no parameter

event_noparm

  • Scriptable Event has parameter (int, float, string, bool, vector3,...)

event_float

Raise Events

You can raise events by code or by the inspector (Enable Debug Field > button Raise Event)

Raise by code

public class Player : MonoBehaviour
{
    public EventNoParam playerAttackEvent;

    public void Attack()
    {
        playerAttackEvent.Raise();
    }
}

Raise by inspector (Enable Debug Field > button Raise Event)

event_noparm

Listener Events

You can listener event by component Event Listener or by code

Listener by component

listener event 2

  • Binding
    • UNTIL_DISABLE : the event is subscribed when OnEnable() and unsubscribed when OnDisable()
    • UNTIL_DESTROY : the event is subscribed when Awake() and unsubscribed when OnDestroy()
  • Event Response Data
    • Event : Drag scriptable event here
    • Response() : Response() works similarly to a button's OnClick, When the above Event is raised, the functions embedded in Response() will be called

Listener by code

  • Use AddListener to subscribe and unsubscribe
 public EventNoParam playerAttackEvent;

    private void OnEnable()
    {
        playerAttackEvent.AddListener(HandleAttack);
    }

    private void OnDisable()
    {
        playerAttackEvent.RemoveListener(HandleAttack);
    }

    void HandleAttack()
    {
        // Attack
    }
  • Use OnRaised to subscribe and unsubscribe
public EventNoParam playerAttackEvent;

    private void OnEnable()
    {
        playerAttackEvent.OnRaised += HandleAttack;
    }

    private void OnDisable()
    {
        playerAttackEvent.OnRaised -= HandleAttack;
    }

    void HandleAttack()
    {
        // Attack
    }

Scriptable Variable

Clone this wiki locally