- Home /
Fire C# Event
I'm finding myself unable to call a previously defined event. When providing unity the following code
Events.cs
using UnityEngine;
using System.Collections;
public class Events : MonoBehaviour {
public delegate void GameOverEvent();
public static event GameOverEvent GameOver;
}
SomeCollider
using UnityEngine;
using System.Collections;
public class SomeCollider : MonoBehaviour {
void OnCollisionEnter (Collision collision) {
if (collision.gameObject.tag == "Stacked") {
Events.GameOver();
}
}
}
I get the following error:
The event Events.GameOver can only appear at the left hand side of += or -= when used outside of type "Events"
Is there any way to solve the issue without creating a static method on Events? Thank you in advance.
the way normal methods work:
other Object ----$$anonymous$$ethod---->Class
the way events work:
Class ----Event----> other Object
only the class can call the event...so implement an OnXxx $$anonymous$$ethod ore something simular and everything should be working
Answer by Jessy · Jun 28, 2012 at 10:57 PM
No. It either needs to be static, or you need a reference. But you should not be thinking about this; what you're trying to do involves bad design, namely poor encapsulation. Instead, fire an event in SomeCollider, and have another class fire GameOver based on that. Unless, of course, you're just defining events in one class, in order to try to be organizational. That's also bad practice – Events is a terrible idea for a class – each class should use events that fit with its meaning, but, this will help you in any case:
Answer by whydoidoit · Jun 28, 2012 at 10:59 PM
An event can only be fired by the class that defines it as the error tells you. You could use a SendMessage or BroadcastMessage instead if you don't want to write a firing function.
Is there some reason why the thing defining the event doesn't run the detection code?
Answer by nkvnkv · Aug 25, 2014 at 08:24 PM
My solution to same problem I have found on address http://www.willrmiller.com/?p=87
UPDATE:
Finally found a non cooked up solution to events and delegates at https://www.youtube.com/watch?v=ihIOVj9t0_E
Your answer
Follow this Question
Related Questions
Subscribers of Delegates? 2 Answers
Question about unsubscribing eventhandlers OnDisable and OnEnable 2 Answers
How do Delegates and Events work? 1 Answer
Stack Overflow error on delegate call 2 Answers
Multiple Cars not working 1 Answer