look at closer

hey everyone, i need some help, i want my capsule look at cube, but i want look at cube closer to my capsule, i just know script : transform.LookAt (“Cube”);, but it’s not look at closer to my capsule, so i need help to look at closer to my capsule. I’ve been looking for a solution on youtube, but did not find any solution, please give me a example cause i’m just beginner on unity3d.
Thanks :smiley:

  • First Store all the objects you want to check in an array easily accessible
  • Then create a reference to the capsule as well
  • Create a foreach inside the Update function foreach cube in the array
  • Check the distance what I also added I don’t know if you want but makes the script easier to make is a limit of how far the capsule should be able to detect the cubes which i used 10

All together the script should look something like this

public Transform[] cubes;
public Transform capsule;
private float minDist = Mathf.Infinity; //For now I set it to Mathf.Infinity so anything can be picked up.

void Update()
{
    foreach(Transform cube in cubes) //Here I check each cube
    {
        float Distance = Vector3.Distance(cube.position, capsule.position); //Here I check the distance of each cube
        if(Distance <= minDist) //Here I check if its closer or "less" than the previous cube
        {
            minDist = Distance; //Here i set the new closest distance
            capsule.LookAt(cube);
        }
    }
}

Hope this helps :slight_smile: