mercredi 28 octobre 2020

When I try to get Random.Range from an Array and set an image I get "IndexOutOfRange" exception

I'm fairly new to programming and want to develop a Game that involves a slot machine. From my research I learned that I should use Arrays for this type of stuff. So I tried to make an array put my 3 images into it and show them random in the update function. When I start the project it shows one image and stops. After that I look at the console and I get a out of range exception. Please help me :/

here is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;


public Sprite[] sprites;  
    public Image image;
    public float StopTime;

void Update()
    {
        RandomingImage();
        

    }

    void RandomingImage()
    {
        gameObject.GetComponent<UnityEngine.UI.Image>().sprite = sprites[UnityEngine.Random.Range(0, sprites.Length)];

    }

    void EndRand()
    {
        enabled = false;
    }

    public void StopRand()
    {
        Invoke("EndRand", StopTime);

    }
    public void StartRand()
    {
        enabled = true;
    }
}



Aucun commentaire:

Enregistrer un commentaire