I'm working on RTS game and need a better way for units to deter each other.
When each unit is doing this, at around 30 units this starts to become very expensive way to run things.
What would be a better way to optimize this:
private void Update()
{
if(target == null)
{
ArrayDetect();
AttackUnit();
return;
}
[SerializeField] private Collider[] colliderArray;
[SerializeField] private List<GameObject> enemyColliders;
private void ArrayDetect()
{
colliderArray = Physics.OverlapSphere(ownAimAtPoint.position, fireRange, layerMask);
foreach (Collider collider in colliderArray)
{
Debug.Log("we hit a", collider); if(!collider.TryGetComponent<Targetable>(out Targetable potentialTarget))
{
return;
}
if (potentialTarget.hasAuthority)
{
return;
}
else
{
enemyColliders = enemyColliders.Distinct().ToList();
enemyColliders.Add(collider.gameObject);
Debug.Log("Found an enemy", potentialTarget);
}
}
}
Physics.OverlapSphere to find colliders in range with layermask tag, then sort through them and add them to a enemy List
then:
private void AttackUnit()
{
//if (enemyColliders.Count == 0) { return; }
foreach (GameObject enemy in enemyColliders)
{
Debug.Log("We got confirmed enemy", enemy);
gameObject.GetComponent<Targeter>().CmdSetTarget(enemy);
//attack the enemy
}
}
go through enemy List and assign each enemy as a target to attack.
question from:
https://stackoverflow.com/questions/65908498/unity-script-c-array-to-list-how-to-optimize-object-detection-in-a-better-way 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…