Hi.
I want to know, can I create my own public events in unity?
I mean events like Start(), OnEnable() and etc.
And I create an event with the name OnFire() and I use it in another script directly? How?
Hi.
I want to know, can I create my own public events in unity?
I mean events like Start(), OnEnable() and etc.
And I create an event with the name OnFire() and I use it in another script directly? How?
You can’t - not directly the way Unity does it anyway.
You can use UnityEvents or C# events to your heart’s content though.
Use it how in another script?
If the method is public, and you know the component type, you can just call the method/function directly.
target.GetComponent<OnFireReceiver>().OnFire();
If you don’t know what components you’d be calling it on, and want to ambiguously call a funciton of some name on all components attached to a GameObject that have a method named that. You can use SendMessage:
https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html
(I personally don’t like this method as it relies on string names, and could accidentally call a method on a script that just happened to be named the same but wasn’t intended to be called)
There’s the ExecuteEvents system which allows doing so by some interface contract which avoids the string issues of SendMessage:
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/MessagingSystem.html
…
But yeah, I don’t know what you necessarily mean by “use it in another script directly”.
Note that there’s 2 general ways discussed so far here. In the messages approach (Start, OnEnable, SendMessage), this is a situation where the receiver doesn’t necessarily subscribe with the dispatcher that it wants to receive the message. It just implements the message callback and it can receive that message arbitrarily.
In an event system like C# events, or UnityEvents. The receiver has to explicitly subscribe with the dispatcher before it can receive the events.
That ExecutEvents/MessagingSystem is more like messaging. In that again you don’t have to subscribe with the dispatcher, but at least you have to obey some contract (in the form of the interface) before you can receive them.
What sort of roles do you want to enforce between the sender/receiver?
How do you want your event/messaging system to behave?
You have lots of options.
Lord of Duct dances around the topic of an abstract “interface” here, but I want to come out and say explicitly:
C# interfaces in Unity are awesome!!
Here’s some of my feverish scribblings about it, as they might be useful in your situation:
Using Interfaces in Unity3D:
https://discussions.unity.com/t/797745/2
https://discussions.unity.com/t/807699/2
Check Youtube for other tutorials about interfaces and working in Unity3D. It’s a pretty powerful combination.