C
C#3y ago
Yonatan

How do I call a null event?

public delegate void MyDel();

public event MyDel MyEvent;

public void LeftClickPressed()
{
if (MyEvent != null)
MyEvent();
}
public delegate void MyDel();

public event MyDel MyEvent;

public void LeftClickPressed()
{
if (MyEvent != null)
MyEvent();
}
In here, the event is always null. I Subscribed to it from a different class so everytime I trigger this event, a function will also run from that second class. However this event never triggers because it is always null. What Am I missing here?
8 Replies
Becquerel
Becquerel3y ago
how are you subscribing to MyEvent? an event is only null if nothing is subscribed to it
Yonatan
YonatanOP3y ago
public void Start()
{
PlayerInput Player = new PlayerInput();
Player.MyEvent += ShootDisk;
}
public void Start()
{
PlayerInput Player = new PlayerInput();
Player.MyEvent += ShootDisk;
}
Start is called at the start of the program. the code I mentioned above is inside the class "PlayerInput".
Becquerel
Becquerel3y ago
ok, looks good and LeftClickPressed gets executed somewhere? oh wait you create a new PlayerInput object in the Start method but that object will die when the method ends along with the event subscription you need to make one PlayerInput and save it
Yonatan
YonatanOP3y ago
Done, but the function will stay subscribed until I Unsubscribe. right?
Becquerel
Becquerel3y ago
yes, or Player is collected by the garbage collector
Yonatan
YonatanOP3y ago
awesome, Thank you! and yea, my problem was I was creating 2 PlayerInput and I though triggering the event of one will also trigger for the others
Becquerel
Becquerel3y ago
ahhhhh yeah if you want that, you'd want to create a static event that way it would live on the PlayerInput type itself, and not instances of it that said... static events can be quite dangerous in terms of causing memory leaks so probably not worth it
Yonatan
YonatanOP3y ago
I Won't deal with them now than, Thank you!
Want results from more Discord servers?
Add your server