- Home /
Create a method that gets called everytime something happens, passing a Transform component to it
[C# only, please] Sorry if this is really simple, but since I'm starting out, I probably missed something.
Lets say I have a EnemyDetector script. It detects all GameObjects within a certain radius, and checking if they have the "Enemy" tag. What I want is something like a delegate (I know a little of what they can do, but after some research I don't know if they can do this) calls all methods subscribed to it, but passing a Transform (or any other component attached to the detected GameObject) of the Enemy while calling it.
Even though I could just do this by simple calling the methods like usual, I feel like there must be a better way with a such a powerful language (C#). Resuming the sentence above, I want to make my code look readable and a little optimized, not a mess.
Thanks to anyone that replies to this.
Answer by FortisVenaliter · Sep 28, 2017 at 07:29 PM
I recommend using the generic UnityEvent class.
You can set it up as a class-scope field:
public UnityEvent<Transform> OnDetected;
You can then set up the callbacks in the inspector (as many as you want) just like you do with a UI button. When you detect an enemy, simply call:
OnDetected.Invoke(transformOfEnemy);
And it should call all the functions you set up in the inspector with the transform you pass as an argument.
Thank you a lot, this was what I needed!
(Also, sorry for answering so late. I say your answer on the day you posted it, but I could not log in to mark it as solved...)
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Speed and efficiency of enabling/disabling component? 1 Answer
ECS Buff/Debuff system 0 Answers
Multiple Cars not working 1 Answer
My function doesn't appears in the OnClick button script 5 Answers