1
\$\begingroup\$

I've delved into scriptable objects in a small hobby project of mine and have to say I very much like them. I'm interested in how they can work with the built-in Unity Events to handle a lot of the communication b/w my player and the UI, but I have some questions regarding performance and best practice.

I stumbled upon a nice pattern I like where you create a SO that keeps track of something like ammo or health and has some public methods like IncreaseAmmo() or DecreaseAmmo() that get called from some other script. When one of those methods is called, they update the amount of ammo and then call Invoke() on an "ammoChangeEvent" unity event. My UI controller is then listening for those events and updates the UI according to the new ammo amount. Pretty slick and simple to me.

The problem/question I have is with performance. I want my ammo bar to recharge over time, which means that while the player's ammo isn't full, I'm calling IncreaseAmmo() in an Update method. This works as intended, but I'm hesitant about calling a method that sends a Unity Event every frame. In the stats gizmo, I can see that whenever my ammo bar is recharging, my FPS drops significantly (granted it's from 800 -> 400 but that seems like it has a performance impact).

So my long winded question is: Is it bad practice to have a Unity Event invoked every frame? Are they expensive and if so, what's the best alternative for something that needs to be "recharging" constantly. I'm not sure a reference to a regular class would be that much better.

Thanks for reading such a long post! Anything helps!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ "How expensive is X" is a question always best answered by profiling. It sounds like you're beginning to do that already, but you shouldn't look at FPS for that purpose - it gives you the reciprocal of the time taken in total, so it's non-linear (a drop from 800 to 400 is the same time cost as 90 to 81) and non-specific (doesn't tell you where the cost is). Run the built-in profiler and look for how many ms you're paying for which functions. It might not be the event that's introducing this cost, but rather the UI layout update for the ammo counter. Only profiling will tell you for sure. \$\endgroup\$ Commented Apr 8, 2023 at 12:15
  • \$\begingroup\$ This is an incredibly helpful answer, thank you. I never knew FPS was calculated like that and had that effect. I see how it's not a great performance metric now. I'll look into the Profiler and see what I can find. Thank you! \$\endgroup\$ Commented Apr 10, 2023 at 18:29

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.