Reputation: 3
I Expected this object to destroy itself once it exceeds the Array's amount, however, it throws an ArrayOutOfBounds. I was wondering if there would be a solution to this problem.
I also tried:
if (ObjectSprite[spriteNumber + 1] == null)
I expected that would work but I'm new to developing so I'm stuck here
public class DestroyableObject : MonoBehaviour {
public GameObject coin;
public int spriteNumber = 0;
public Sprite[] ObjectSprite;
void Update ()
{
SpriteUpdate();
}
void SpriteUpdate()
{
this.GetComponent<SpriteRenderer>().sprite = ObjectSprite[spriteNumber];
if (spriteNumber > ObjectSprite.Length)
{
Instantiate(coin, this.transform.position, Quaternion.identity);
Destroy(this.gameObject);
}
}
}
Upvotes: 0
Views: 40
Reputation: 91555
You're trying to access the array before checking if the spriteNumber
is greater than the array. You should first check if the spriteNumber
is out of bounds, then attempt to access the ObjectSprite
.
void SpriteUpdate()
{
// if we're within the bounds of the array
if (spriteNumber < ObjectSprite.Length)
{
this.GetComponent<SpriteRenderer>().sprite = ObjectSprite[spriteNumber];
}
// if we're outside the bounds of the array
else
{
Instantiate(coin, this.transform.position, Quaternion.identity);
Destroy(this.gameObject);
}
}
Note that the condition inside the if statement has been flipped; It will only execute the code inside the if block when the spriteNumber
is less than the array length. An else
clause is also provided which will instantiate the coin and destroy the object when that previous condition is no longer true (it's out of bounds of the array).
Upvotes: 2