Skip to content

Observer pattern

Jiufen edited this page Apr 1, 2021 · 1 revision

👀 Observer pattern 👀

The observer pattern consist on delegating all the logic to a manager through the use of a notification to that manager. This logic in unityand c# is really easy to implement, through the use of Events

Here is a simple implementation to give you and idea of how to start:

PointOfInterest.cs

using System;
using UnityEngine;

public class PointOfInterest : MonoBehaviour
{
    public static event Action unlockAchivement;
    [SerializeField] private string poiName;
    public void AchivementUnlocked()
    {
        if(unlockAchivement!=null) 
            unlockAchivement.Invoke(this);
    }
    
}

AchivementManager.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AchivementSystem : MonoBehaviour
{
    private void Start() {
        PointOfInterest.unlockAchivement += unlockAchivementWithName; 
    }

    private void unlockAchivementWithName(PointOfInterest poi)
    {
        // Do the achivement unlock || add it to playerPrefs
    }
}

Clone this wiki locally