I’m a new learner on Unity. Meeting a problem when trying to run an easy example of Delegate and Event.
My code is as below:
- create two empty Objects called Receiver and Sender.
- create two scripts and attach them to the related Objects.
- then the scripts as below, but in the console showing “PlayerDiedInfo is NULL”, which should refer that the Event of PlayerDiedInfo is not created. But Dont know where the problem is.
Receiver.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Receiver : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Sender.PlayerDiedInfo += PlayerDiedListener;
}
void PlayerDiedListener()
{
print("Event has called this function");
}
}
Sender.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sender : MonoBehaviour
{
public delegate void PlayerDied();
public static event PlayerDied PlayerDiedInfo;
void Start()
{
if(PlayerDiedInfo != null)
{
print("PlayerDiedInfo isnt null");
PlayerDiedInfo();
}
else
{
print("PlayerDiedInfo is NULL");
}
}
}