I can not figure out how to use delegates and events in a Unity project.
I have an observer class

public class Observer : MonoBehaviour { #region Singletone private static Observer _instance; public static Observer Instance { get { if (!_instance) { _instance = FindObjectOfType(typeof(Observer)) as Observer; if (_instance == null) { Debug.Log("Error!"); } } return _instance; } } #endregion public delegate void GivePoints(int value); public static event GivePoints OnGivePoints; } 

I have a Death method in a zombie script:

 public void Death() { if (Observer.OnGivePoints != null) { Observer.Instance.OnGivePoints(5); } } public void GivePoints(int value) { Debug.Log(value); } 

Also in the start method in the zombie script it is written:

 void Start() { Observer.OnGivePoints += GivePoints; } 

It seems to have done everything correctly, but in the Observer.OnGivePoints != null swears at OnGivePoints , writes: " Observer ')

I used the Observer pattern for this video tutorial, and I also took the code from there - https://www.youtube.com/watch?v=qwQ16sS8FSs , for some reason everything works for him

  • Why do you have a static event? - Sergey
  • so that you can call him everywhere, or am I doing something wrong? I did the guide - Vitaly Belousov
  • Well, you read about Singleton - it is already accessible by instance, it does not need a static property in this case. - Sergey
  • but this does not solve my problem? - Vitaly Belousov

2 answers 2

Hello. You trigger an event in a zombie class, not an Observer class.

Those. you have an error here:

I have a Death method in a zombie script:

 public void Death() { if (Observer.OnGivePoints != null) { Observer.Instance.OnGivePoints(5); } } 

This line of Observer.OnGivePoints! = Null calls the event, which you are told in the error message - that you can only subscribe or unsubscribe from the event (+ = or - =), and you should check it for null in the Observer class. Those. checking for null and calling the event you need to transfer to the class where this event is announced, or declare a delegate and an event in a zombie class.

    The meaning of the event is that it can only be called from the object in whose class it is declared. And from the outside you can only subscribe or unsubscribe from it.

    I understand that after the death of a zombie, do you need to add player points? Then it will be more logical to create an event in the zombie class and call it after the death of the zombie from inside the same class.

    In the video tutorial, the same event is necessary for causing damage to the enemy. The player deals damage, so an event has been announced in the player's class. From the class of the player event and called.

    • I want to organize the Observer pattern for this article, but somehow it doesn't work - habrahabr.ru/post/212055 - Vitaly Belousov