- Home /
How do I access a static event in another function?
I have a timer class, which runs my clock, and a MainSimulator class, which does the game logic's heavy lifting. Every time the in-game minute changes, I would like the timer to message the simulator to execute whatever code I've added to the event. In the simulator class, I have:
public delegate void MinuteTick(); //Everything that executes when the minute changes is added to this
public static event MinuteTick OnUpdateMinute; //This is the event that the timer needs to call every minute to run the above delegate
To trigger this, in the timer class I have a function that runs on update:
public void CheckMinutes(float currentMinute){
if (currentMinute != lastMinute) {
lastMinute = currentMinute;
if (MainSimulator.OnUpdateMinute != null)
MainSimulator.OnUpdateMinute(); //Message everything subscribed to OnUpdateMinute
}
}
However, this produces a pair of errors on the last line and the (blank) line below it, "The name OnUpdateMinute does not exist in the current context", and providing it a component reference to MainSimulator produces a different error, "The event OnUpdateMinute can only appear on the left hand side of += or -=", which is weird since I thought I was using it as the left-hand argument to verify it's not empty before I run it... am I using events completely wrong?
Answer by .Talon · Dec 20, 2014 at 01:48 PM
You can not execute an event from inside another class. Add an UpdateMinute function in your simulator which calls OnUpdateMinute and call that function in CheckMinutes.
Hmm, that works, thank you. :)
This is likely a silly question, but is there a way to do this that doesn't involve retaining a reference to the simulator class in the timer? I'm trying to keep my program as decoupled as possible, and lots of interdependancy like this makes me a bit nervous.
Well, you have to call the function somewhere and that is either inside the class or from somewhere else. How about merging the two classes into one class that handles all the timer relevant things?
That might work, although I'm also hesitant to cram everything into a single pot- what I'm doing for now is simply caching the reference in the timer for performance's sake, I'll probably go back and look at refactoring/cleaning things up once everything is working :)