Rotate towards target, prefabs?

Hello -

I am making a game in which the player’s car and the AI cars must grab coins. I have the code for the player car working just fine.

The problem is with the AI cars. The AI car rotates toward the first target coin, a prefab, using code based on Unity - Scripting API: Vector3.RotateTowards . However, if the player grabs the coin first, and a nw coin spawns, the AI car does not rotate towards the new coin prefab.

Code is as in the link provided, and the target object is my coin prefab (pulled from the prefab folder):

using UnityEngine;

// To use this script, attach it to the GameObject that you would like to rotate towards another game object.
// After attaching it, go to the inspector and drag the GameObject you would like to rotate towards into the target field.
// Move the target around in the scene view to see the GameObject continuously rotate towards it.
public class AICarController : MonoBehaviour
{
    // The target marker.
    public Transform target;

    // Angular speed in radians per sec.
    public float speed = 1.0f;

    void Update()
    {
        // Determine which direction to rotate towards
        Vector3 targetDirection = target.position - transform.position;

        // The step size is equal to speed times frame time.
        float singleStep = speed * Time.deltaTime;

        // Rotate the forward vector towards the target direction by one step
        Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetDirection, singleStep, 0.0f);

        // Draw a ray pointing at our target in
        Debug.DrawRay(transform.position, newDirection, Color.red);

        // Calculate a rotation a step closer to the target and applies rotation to this object
        transform.rotation = Quaternion.LookRotation(newDirection);
    }
}

Note: at this point I am only rotating toward the target, not moving towards it. Baby steps.

Any pointers on what I should be looking for? Thanks, regards.

You need to set the target as the coin you want your AI to rotate towards. So when a new coin spawns, change target in ‘AICarController’ to the new coin’s transform.

In the future if there are multiple coins on screen, you will want to iterate through all the coins, compare the distance from the AI to each coin and set the target to the closest coin.