Hello, I’m trying to use an OnTriggerEnter to build a list for the units, working on having an attack at will so they will auto-attack the closet unit, but it’s not working.
In the RPG project, I have the same code and setup and it works fine, was wondering if it had anything to do with the networking?
This is on a child object on the Unit and takes in the Unit’s Targeter.
public class TargetCollider : MonoBehaviour
{
Collider trigger;
[SerializeField] Targeter targeter = null;
void Start()
{
trigger = GetComponent<Collider>();
if (trigger)
{
trigger.isTrigger = true;
}
}
private void OnTriggerEnter(Collider other)
{
targeter.OnUnitEnter(other);
}
private void OnTriggerStay(Collider other)
{
targeter.OnUnitStay(other);
}
private void OnTriggerExit(Collider other)
{
targeter.OnUnitExit(other);
}
}
This is in the Targeter script.
public void OnUnitEnter(Collider other)
{
if(other.TryGetComponent<Targetable>(out Targetable target))
{
if (target.hasAuthority)
{
return;
}
attackTargets.Add(target.gameObject);
}
}
public void OnUnitStay(Collider other)
{
float distanceToClosestTarget = Mathf.Infinity;
List<GameObject> deadTargets = new List<GameObject>();
foreach (GameObject target in attackTargets)
{
float distancetoTarget = (target.transform.position - this.transform.position).sqrMagnitude;
Health health = target.GetComponent<Health>();
Targetable tar = target.GetComponent<Targetable>();
if (health.IsDead())
{
deadTargets.Add(other.gameObject);
}
if (attackTargets.Count != 0 && attackAtWill == true && targetAble == null)
{
if (distancetoTarget < distanceToClosestTarget)
{
distanceToClosestTarget = distancetoTarget;
targetAble = tar;
}
}
}
foreach (GameObject dead in deadTargets) //This section does the removing outside of the loop
{
attackTargets.Remove(dead);
}
return;
}
public void OnUnitExit(Collider other)
{
attackTargets.Remove(other.gameObject);
}
It works in my RPG project