- Home /
Animator.SetFloat causing large CPU Usage
I am trying to optimize my games performance and I noticed that one of my scripts is using 19% of the CPU Usage. This script is attached to all of my troops (50 - 100+ units) in an RTS Style game and is used for getting the correct number ("SpeedPercent") for an Animation blend tree. When disabling all the troops with this script on them the FPS jumps up from ~15 FPS to ~50 FPS. I'm not sure what I can do improve this script or set the animator float more efficiently. Also, the editor loop is taking up a lot of CPU Usage (46.4%) but I've been told this is from running the profiler and will go away once the profiler is closed.
Below is the script.
public class CharacterAnimator : MonoBehaviour {
const float locomotionAnimationSmoothTime = .1f;
public float SpeedPercent;
public NavMeshAgent agent;
// Update is called once per frame
void Update () {
SpeedPercent = agent.velocity.magnitude / agent.speed;
animator.SetFloat ("SpeedPercent", SpeedPercent, locomotionAnimationSmoothTime, Time.deltaTime);
}
}
Answer by Anaxis_Studio · Sep 15, 2019 at 11:51 PM
1) Multithread your code https://docs.unity3d.com/Manual/JobSystemOverview.html
2) Use a coroutine to limit executions
For example, limit the execution rate to every 1/10th of a second rather than once per frame.
Update()
{
StartCoroutine(someCoroutine());
}
private IEnumerator someCoroutine()
{
Debug.Log("Tick");
yield return new WaitForSeconds(.1f);
}
3) What about other optimisations outside of this? are you GPU instancing clone meshs that share a material? (trees, grass, tanks, etc)
4) Built-in, URP or HDRP? If you're using URP or HDRP consider using the ECS (https://docs.unity3d.com/Packages/com.unity.entities@0.0/manual/index.html).
4) Read this document from Unity about diagnosing and fixing issues related to coding (https://learn.unity.com/tutorial/fixing-performance-problems#5c7f8528edbc2a002053b594) You might find some useful information.