The question is answered, right answer was accepted
Destroy gameobjects in an array using a for loop.
As stated in the title, I am trying to destroy gameobjects that are within a certain range of my Player object at the moment I am calling the method. For some reason, after I run it once, it no longer works, no matter how much my ammo is, or how many times I press the key it is bound to. Anyone got any idea why it is happening?Thanks!
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
DestroyEnemies();
}
scoreBoard.text = $"SCORE : {Score}";
ammunitionCount.text = $"AMMO : {Ammunition}";
}
//Enemy destroyer method
private void DestroyEnemies()
{
LayerMask mask = LayerMask.GetMask("Ground");
Collider[] enemiesInRange = Physics.OverlapSphere(this.transform.position, 10f, mask);
if (enemiesInRange.Length != 0)
{
for (int i = 0; i < enemiesInRange.Length; i++)
{
if (Ammunition <= 0)
{
break;
}
Destroy(enemiesInRange[i].gameObject);
Debug.Log("Got one!");
Ammunition--;
Score++;
}
}
}
//Collectible objects destroyer
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Collectible")
{
Destroy(collision.gameObject);
Ammunition++;
}
}
Good day.
Did you debugged the code? Is the method DestroyEnemies() beeing called ?
is this true?
if (enemiesInRange.Length != 0)
and this?
if (Ammunition <= 0)
and this is generating an array?
Collider[] enemiesInRange = Physics.OverlapSphere(this.transform.position, 10f, mask);
As you can see, we can not help you if you come here, post a code, and ask... YOU are the only person that can find why is not working. You need to find what line is not giving you the expected result. And if even then you dont understand whay, then come to ask, why one specific comand or methid ios not doing what you think it shoiuld do.
Bye!
Ok, now that is embarrassing. Turns out I just didn't apply the proper Layer to the prefab I was instantiating, only to the Gameobject in the scene. Code works fine. Thanks for the suggestion to Debug every part of the method, that got me on the right track!