Hello. I have an enemy object that throws projectiles and there are several of them scattered around the map, it is expected that when the player is close to one of the enemies it will shoot, but the enemy that is nearby does not shoot, another that is far away from the player is who shoots, if I can help, I will be grateful.
I used an object as a distance manager did not give, then put this checker in the Police script, did not give, did a lot and did not give.
I saw the DistanceManager and the Police script, and I don't find any error. Did you check if the distance value you assign from inspector is a low value like 1.5f? And for easier debugging, do this. Code (CSharp): using UnityEngine; public class ShootWhenIsClose : MonoBehaviour { [SerializeField, Tooltip("Enemy object")] private GameObject police; [SerializeField, Tooltip("Distance that player need to get close to shoot")] private float distance; [SerializeField, Tooltip("Projectile to instantiate")] private GameObject bullet; // Player private GameObject player; private void Start() { player = GameObject.FindGameObjectWithTag("Player"); } void Update() { // Take distance between player and enemy float dist = Vector2.Distance(player.transform.position, police.transform.position); // If 'distance' is bigger that 'dist'. Then shoot if (distance >= dist) Shoot(); } void Shoot() { Instantiate(bullet, transform.position, Quaternion.identity); } }
And for Raycast I think it is not necessary to put distance. Because this will draw a line between two points (in this case, the transformation and the point you indicate), and check if the object with the layer player is inside. So, if the player is inside, this will return a Raycast with the information of the target player. For this you can use a Linecast, it's exactly the same. Here the link for Linecast
Yes, the enemies shoot when the player is far away and stop when they are near. If you are using raycast in the video. You might have put the wrong points. By the way the distance that goes on the raycast, it should be the distance it gives you from your transform and crossHair. Not a distance entered