Hey guys, I’m very new to Unity so I don’t know what I would use to do this, but I would like to have an enemy rotate towards a player if it is within a certain radius. I’ve already managed to use some code but it doesn’t give me the range effect that I want. Any help? Here’s the code I currently have.
If you just want a simple solution, put a Sphere Collider on your turret and enable the “IsTrigger” checkbox. Make sure your player has a collider as well. Then attach a rigidbody to either your turret or your player.
After you have attached those 3 components to your objects, you are ready to edit your turret script. Create a function on your script called OnTriggerEnter(). This function will be called by unity whenever your turret collider touches the player’s collider. Put your turret code there. See the example in the Unity documentation for reference:
Note: you have to attach a rigidbody to either your turret or your player or else Unity will not call OnTriggerEnter on the turret. If you don’t want to have the physics run on the rigidbody, then just enable the “Is Kinematic” checkbox on the rigidbody. This will allow OnTriggerEnter() to work, but the physics will not interfere with your gameplay.