The question is answered, right answer was accepted
Why my NPCs shoot the player but not other GameObjects?
Hi folks! I've been studying Unity and C# for a while now, but I'm having a hard headache with this problem. It looks like a bug, but it can be a scripting error (AKA myfault).
Can anyone figure out why, using this script, my NPCs do shoot at the Player when I type "Player" on targetTag, but don't shoot other NPCs? Even if I change the NPCs tag to Player, they won't do it!
If I wanted them to shoot the player, the script would be just fine: the only shoot when they have a clear line of sight and on a random basis...
using UnityEngine; using System.Collections;
public class FireRangedWeapon : MonoBehaviour {
[SerializeField] private string targetTag;
[SerializeField] private float power = 10.0f;
[SerializeField] private float weaponRange = 20f;
[SerializeField] private int minReloadTime;
[SerializeField] private int maxReloadTime;
private float reloadTime;
private GameObject target;
public GameObject projectile;
void Start ()
{
StartCoroutine (Attack ());
}
IEnumerator Attack()
{
FindClosest ();
if ((Vector3.Distance (transform.position, target.transform.position) <= weaponRange) && !Physics.Linecast(transform.position,target.transform.position,1))
{
transform.LookAt (target.transform);
GameObject newProjectile = Instantiate(projectile, transform.position + transform.forward, transform.rotation) as GameObject;
newProjectile.GetComponent<Rigidbody>().AddForce(transform.forward * power, ForceMode.VelocityChange);
}
reloadTime = Random.Range (minReloadTime, maxReloadTime);
yield return new WaitForSeconds (reloadTime);
StartCoroutine (Attack ());
}
void FindClosest()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag(targetTag);
GameObject closest = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
target = closest;
}
}
Answer by jacupiri · Aug 06, 2016 at 11:35 PM
Even though no one answered my question, I found out by myself that it was a matter of Layers, because I was using a Linecast as part of one of the "if" statements. Since the gameObjects were on the same layer where the Linecast was looking for obstacles, they never shot each other...
So I just set the NPCs to another layer and that was the end of it!