Can this script be better optimized?

Hello!

I wrote a simple script for enemy cars to follow the player. I also have other scripts on the enemy cars that control smart actions such as shooting, ramming etc…

When I look in the profiler I see that this script Update is taking over 70% resources. Is there any way I can make this script better optimized for mobile devices?

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class BOTAI : MonoBehaviour {

    private Rigidbody rb;
    public int AddForceAmount;
    public int bothealth;
    public Transform PlayerToLookAt1;
	public Transform PlayerToLookAt;
	private Text missileText;
	Quaternion targetRotation;
    // Use this for initialization
    void Start ()
    {
		//don't forget to change AddForceAmount Random.Range in ProxFront.CS too!
		AddForceAmount = Random.Range (1400, 2600);
        PlayerPrefs.SetInt("AddForceAmount", AddForceAmount);
        rb = GetComponent<Rigidbody>();
		PlayerToLookAt = GameObject.FindWithTag("Player").transform;
		PlayerPrefs.SetInt("CarID", 2);
		missileText = GameObject.Find("missileText").GetComponent<Text>();
		missileText.text = "Missiles:" + "" + PlayerPrefs.GetInt ("missileamount");
    }
	
	// Update is called once per frame
	void Update ()
    {
			AddForceAmount = PlayerPrefs.GetInt ("AddForceAmount");
			Vector3 PlayerToLookAtTransform = new Vector3( PlayerToLookAt.position.x, this.transform.position.y, PlayerToLookAt.position.z);
			this.transform.LookAt (PlayerToLookAtTransform);
			rb.AddForce (transform.forward * AddForceAmount);
    }
}

Thanks in advance for your ideas!

You’re not doing anything bad your code. Nothing really to optimize here.

However, you’re using physics. You have a rigid body, and you’re applying forces to it. And I imagine you probably have more than one game object running this same script with physics calculations? Physics, in general, are rather computationally heavy. And while it might be fine on a PC, a mobile device can definitely have issues dealing with it.

Your best option would be to remove all the rigid bodies and forces and just modify the transform directly. It won’t look as fancy, but it will run much faster.