I use a lot of events for my game, and try to never code inside Update(). Now I ran into an issue though, I have som AI and some waypoints, when the AI reaches a waypoint I want them to lookAt a specified transform and then play an animation.
However, using just LookAt(target) will snap the AI rotation, I want it to slowly turn towards its target, then play animation.
Is there some way I can do this in a neat way outside the Update() loop?
Here is some code that should do what I need if put inside an Update() loop:
var q = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.RotateTowards(transform.rotation, q, rotateSpeed * Time.deltaTime);
I still have no idea where this comes from. There’s nothing wrong with Update(). Please get over it and stop repeating this silliness.
I made a post about turret turning, and I did it by driving independent scalar angle directions (i.e., one float per axis of rotation). Here’s what I wrote:
Since I have literally thousands of units my game would die if I did everything in update.
Sure I could use a bunch of delay timers but that looks like crap and I find it unreadable, so I’ll keep doing it this way. Didnt know it was a “thing”. But u seem like ud be fun to work on a project with…
Hol’up, having thousands of coroutines is actually faster than having thousands of Updates running? I’m curious did you actually try Update or you went straight to another implementation because you thought it was going to be slower?
If I recall correctly every time you launch a coroutine you’re piling garbage up on the heap, so you might be trading up your performance (if there is indeed a performance boost) for worse memory management.
Yeah many short Coroutines would be worse, at least from what I’ve observed. While long Coroutines seem to be OK. Using update with delay timers is probably better for performance 99% of the time, which is why I use it to control my AI movement inside Update. I just find it to be rly messy using a bunch of delay timers, that is simply a personal preference. Whenever I need sequencing I use Coroutines, and for (almost) everthing else I use events.
My state machine controlling all my units runs in a coroutine that is updated every .5 seconds, this could just as well be controlled in an Update method ofc. But I like the simplicity and control.
My scripts still only use about 3-4% of my performance with hundreds of units walking around, while 45% goes to some un-optimized rendering and the rest to the Editor.
It would be interesting to see an updated benchmark of how much worse it is for performance using Coroutines than updates though, since most of those threads are really old.