- Home /
Third Person Controller is very CPU intensive
I've been testing my game out and it started getting very laggy, I checked the unity profiler and it states that the Third Person Controller is very intensive, I need the TPC because without it their is no game, someone please help me out here. Heres the code if you need to look at it:
void Update()
{
float horizontal = joystick.Horizontal;
float vertical = joystick.Vertical;
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
killCounter.GetComponent<Text>().text = kill.ToString();
if (direction.magnitude >= 1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
controller.Move(direction * speed * Time.deltaTime);
animator.SetFloat("MovementSpeed", 1);
}
if(direction.magnitude <= 0f)
{
animator.SetFloat("MovementSpeed", 0);
dustTrail.Play();
FindObjectOfType<Audio>().Walk();
}
if(kill >= desiredKills)
{
light.color = (Color.cyan);
skull.SetTrigger("Extinguished");
}
}
Answer by unity_ek98vnTRplGj8Q · Oct 23, 2020 at 05:47 PM
Calls like FindObjectOfType and GetComponent can cause serious performance issues if used every frame. Assuming that you the objects you are finding are always the same, you should find the component once and save the result.
private Text killCounterText;
private Audio audio;
void Start(){
killCounterText = killCounter.GetComponent<Text>();
audio = FindObjectOfType<Audio>();
}
void Update(){
killCounterText.text = kill.ToString();
audio.Walk();
}
Answer by rh_galaxy · Oct 23, 2020 at 05:54 PM
In that piece of code the only thing that I see you can optimize is
killCounter.GetComponent<Text>().text = kill.ToString();
FindObjectOfType<Audio>().Walk();
Find and GetComponent should be avoided in Update().
dustTrail.Play();
Sometimes particle systems can cause frameskips when they are started, but it is possible to fix it, not sure if it's that, but you do Play every frame, and Audio Walk every frame.
Otherwise it's down to what code that runs when you do this, you have to follow the code further
controller.Move(direction * speed * Time.deltaTime);
FindObjectOfType<Audio>().Walk();
You can also put in timing code to meassure certain parts of the code.
float t1 = Time.realtimeSinceStartup;
//code to meassure
Debug.Log("Time taken: " + (Time.realtimeSinceStartup - t1) * 1000.0f);
Your answer
Follow this Question
Related Questions
CPU Usage Question (iOS) 0 Answers
iPhone Performance Question relating to CPU-WAITS-GPU 1 Answer
Profiler Windows - What is "Others" 1 Answer
Low FPS with no shown reason 2 Answers
Terrain.Heightmap.RenderStep3 taking 90 % of CPU. Why ? 2 Answers