Skip to main content

com.homemade.pattern.observer

info

Version: 1.0.1
Github: Link
Dependencies:

This is simple package for observer, can use in any project.

1. Import

Download from my registries

  • Open Package Manager in Unity.
  • Select Packages tab: My Registries.
  • Download package: com.homemade.pattern.observer

Follow the setup: Click here.

Import from github

Follow this guide: Click here.

2. How to use

note

Before use, you need to create a script name EventID.cs

public enum EventID
{
StartGame,
EndGame,
}

Then you can use it more specific in any event

using com.homemade.pattern.observer;

3. Example

Register/Remove listener

using com.homemade.pattern.singleton;

public class PlayerManager : MonoBehaviour
{
private void Awake()
{
Observer.Instance.RegisterListener(EventID.StartGame, OnStartGame);
}

private void OnDestroy()
{
Observer.Instance.RemoveListener(EventID.StartGame, OnStartGame);
}

private void OnStartGame(object obj)
{
Debug.Log("Start game");
}
}
tip

Instead of using

Observer.Instance.RegisterListener(EventID.StartGame, OnStartGame);
Observer.Instance.RemoveListener(EventID.StartGame, OnStartGame);

You can use

this.RegisterListener(EventID.StartGame, OnStartGame);
this.RemoveListener(EventID.StartGame, OnStartGame);

Posting event

using com.homemade.pattern.singleton;

public class GameManager : MonoBehaviour
{
private void Start()
{
Observer.Instance.PostEvent(EventID.StartGame);
}
}
tip

Instead of using

Observer.Instance.PostEvent(EventID.StartGame)

You can use

this.PostEvent(EventID.StartGame)

Passing value

You pass any type of value in method PostEvent

using com.homemade.pattern.singleton;

public class GameManager : MonoBehaviour
{
private void Start()
{
int level = 1;

Observer.Instance.PostEvent(EventID.StartGame, level);
}
}

You need to parse to the correct value type that was passing from the PostEvent

public class PlayerManager : MonoBehaviour
{
private void OnStartGame(object obj)
{
int level = (int) obj;
Debug.Log("Start level: " + level);
}
}

You can checkout this article, this package is based on it.