简体   繁体   中英

Arrayoutofbounds before destroying Unity3D GameObject

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);
        }
    }
}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM