- Home /
The question is answered, right answer was accepted
How to create a custom "On..." method?
Hello. I would like to know how do I go about making a custom "On..." method. When I say an On method I mean a method like OnValueChanged or OnCollisionEnter. A method that is called in any class that has the method when a certain event occurs.
For example if I have a class for a rolling ball and the class keeps track of how much the ball moves and calls a method whenever it rolls 1 meter. And then in another class I could have the method "OnBallRollOneMeter ()" that gets called. The idea I have is like how OnCollisionEnter gets called whenever a rigidbody collides with something.
I just like to know if this is possible and could someone tell me how to do it. Thanks! (Preferably in C#)
Answer by LK84 · Dec 19, 2016 at 05:47 PM
You can use events.
First define a delegate: public delegate void BallRollHandler(object sender, EventArgs e)
Then witin the rolling ball class you define public event BallRollHandler OnBallRoll;
In your code when the ball has rolled 1 meter you can raise the event:
if(distance==1)
{
if(OnBallRoll!=null)
OnBallRoll(this,EventArgs.Empty);
}
Note: Event Args don't need to be empty. You can use it to transfer all kind of data.
In the other class you first need to make a reference to the specific instance of the rollin ball class and then assign your method as a EventListener:
[SerializeField] BallRollClass YourBallInstance;
void Start()
{
YourBallInstance.OnBallRoll+=OnBallRollOneMeter;
}
void OnBallRollOneMeter(object sender, EventArgs e)
{
}
Follow this Question
Related Questions
On Void Called 2 Answers
How would I detect a right click with an event trigger? 3 Answers
Generalized call of specific methods 1 Answer
Event and methode names for C# 1 Answer