C# script to make AI move once looked at

Is there a C# script that I can use to make the AI move towards the player once looked at?

I feel it’s in bad interest to straight up give code for problems like this as it forgoes opportunities to learn. So instead I’ll detail a few steps that may help.

You’ll want to deal with ray-tracing if you want your AI to not follow you after looking at them through walls, most likely you’ll want walls to block the following behavior. Check out Physics.Raycast

Raycasting can be expensive, so if you have many object raycasting often this could be a performance hit. There’s a faster means to determine whether you’re looking at the object, although it does not take into account if the object is behind walls, this is called the Angle between Vectors. If you know the vector that defines the direction the player is facing, then you create another vector by taking the objects position, and subtracting the position of the player eyes. Then you can get the angle between vectors (Check out Vector3.Angle), if the angle returned by that function is small enough, that means you’re looking within an angle close to the target object.

Thus with these two systems together you can check the Angle between Vectors first, and only if the angle is small enough, then use raycasting. If you set your angles right then any time you’re looking at the object, the angles will be in range, and in the cases where it’s not, you’ll be saving many raycasts.

This does leave the actual following the player part entirely to you, however there are a good few tutorials out there that explain basic AI if you aren’t familiar already, it shouldn’t be difficult to adjust what you see to work only once looked at (deactivating and activating components and setting/unsetting targets etc).