My turrets have some strange behaviour in situations like in below photo. I guess this happens because my turret rotates first to bottom enemy and after to second enemy and loop continues.
So, my ideea is:
- The enemies in turret range will be stored in an array
- Every enemy which exit the turret range will be removed from the array
- The turret
brain
or rotation is triggered in Update function. It will check from index 0 to index 20. When it finds the first indexed which is NOT null, then it rotates and break so it wont rotate to the next enemy which is in the turret range (aka indexed in our array)
It relatively works, i mean it really works. At some point, when Unity triggers me an error like in the below photo and the turret doesn’t rotate anymore. This happens only to some turrets. Every turret has his own script.
I’m just lost, idk what to do/think and i wasted already 4 hours on this crap.
Here are my scripts:
The error comes from this function.
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
int ArrayIndex = Array.IndexOf(triggeredEnemies, collision);
if (ArrayIndex != -1)
{
if (triggeredEnemies[ArrayIndex] != null)
triggeredEnemies[ArrayIndex] = null;
enemiesInArray--;
}
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
triggeredEnemies[enemiesInArray++] = collision;
}
Collider2D[] triggeredEnemies = new Collider2D[20];
public int enemiesInArray = 0;
void Update()
{
for (int i = 0; i < 20; i++)
{
if (triggeredEnemies[i] != null)
{
Vector3 enemyPosition = triggeredEnemies[i].transform.position;
Vector3 vectorToTarget = (enemyPosition - transform.position).normalized;
float Angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
Quaternion quaternion = Quaternion.AngleAxis(Angle, Vector3.forward);
lerpPercent = Mathf.MoveTowards(lerpPercent, 1f, Time.deltaTime * 1.35f);
transform.rotation = Quaternion.Slerp(transform.rotation, quaternion, Time.deltaTime * RotationSpeed);
if (lerpPercent >= 0.8f)
inVision = true;
break;
}
}
}