- Home /
How to make a function like OnEnable that fire by itself when specific event occurs?
I just don't know how to professionally describe what I'm trying to accomplish and how it's called in programing world but I hope that you'll get it.
In unity we have those functions like OnEnable, OnTriggerEnter etc. that fire when specific event occurs in the game and my question is how to make such a custom function? How are they made?
Like I want some class to have this kind of funcion that I don't need to call and it's called by itself when something occurs( I guess it has something to do with inheritance) and you can define it or not but it still exists behind the scenes.
Maybe on the example it will be cleaner:
public class RandomClass : MonoBehaviour {
private void OnEnable() // It's called when game object is enabled
{
//you can define it if you need it or not and delete function but it's still here all time for use
}
private void OnSomethingHappened() // It's called when Something defined by me happened
{
//I want this to be definable if I need it or not and delete function but still be here all the time for use
}
}
So let's say I have a special button on the scene. Whenever I press it I want to call function OnSpecialButtonPress() on every class that implements it. It would look like so:
public class UseButtonClass : MonoBehaviour {
//I wanna know when button was pressed
void OnSpecialButtonPress()
{
print("Yay I pressed it!!");
}
}
public class DontUseButtonClass : MonoBehaviour {
//i dont care about button so i dont implement OnSpecialButtonPress() function
//but I could if I wanted
}
I hope you got what I'm trying to accomplish
Answer by Kciwsolb · Apr 25, 2018 at 06:13 PM
You get the option to implement those methods because your scripts inherit from MonoBehavior. If you wanted to make something similar you would have to make all of your classes inherit from another class that you have those methods in. I doubt this is what you want. More than likely you are interested in either Unity Events or C# delegates and events.
Unity Events: https://unity3d.com/learn/tutorials/topics/scripting/events
C# Delegates / Events: https://msdn.microsoft.com/en-us/library/17sde2xt(v=vs.85).aspx