Hey everyone,
I haven’t studied programming in school so this question might seem a little strange to some people here, but I need your help understanding what I’m doing wrong and since I can’t ask a question on stackoverflow because my questions always get down voted for some reason but I’ll try my best to explain everything.
So I’m trying to use the observer pattern in my game since it decouples the scripts from each other and generally make the code more efficient and less prone to errors so…
I have 2 scripts the first one is called Scanner and the second is one is called Product.
Scanner script:
using UnityEngine;
using System;
public class Scanner : MonoBehaviour
{
public static Action<Color> OnProductHit;
private Color scannerColor = Color.yellow;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Product"))
{
OnProductHit?.Invoke(scannerColor);
}
}
}
Product code:
using UnityEngine;
public class Product : MonoBehaviour
{
private Color productColor = Color.yellow;
private void OnEnable()
{
Scanner.OnProductHit += ScanColor;
}
private void OnDisable()
{
Scanner.OnProductHit -= ScanColor;
}
private void ScanColor(Color _scanColor)
{
if (productColor == _scanColor)
{
Debug.Log("Colors match");
}
else
{
Debug.Log("Colors don't match");
}
}
}
As you can see from the Scanner script I’m calling the event OnProductHit from the OnTriggerEnter method, and the Products scripts subscribe to this event in the OnEnable and in the OnDisable methods but since this event OnProductHit is STATIC which means if I have more than one scanner object in the scene the method ScanColor() will be called as many times as how there are scanner objects in the game.
I watched this cool Observer pattern video on youtube and I asked him the same question and I got this reply from him.
I think his solution might work but I don’t think its good enough since all the events will still run and then check for the condition whether is true or false, like what if I have 15 objects in the scene the again all of the static events in these objects will still run 15 times and check for the condition inside of them making the code extremely inefficient.
I know that there is something that I don’t understand or better solutions using the observer pattern, so if anyone have an idea this question please do share it here.
Thank you.