Random. Range Only Giving One Output

Random. Range Only Giving One Output

I have a problem. I'm trying to randomize the background image whenever I start the game but the output from "BackgroundImageNumber" is always 1 no matter how many times i reroll. Thanks in advance.

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

public class MenuBackgroundChooser : MonoBehaviour
{
    Image BackgroundImage;
    int BackgroundImageNumber;
    
    public Sprite Background1;
    public Sprite Background2;
    
    void Awake()
    {
        BackgroundImage = GetComponent<Image>();
    }
    
    void Start()
    {
        //Set the second nuber to the number of images and increase the switch when adding a background
        BackgroundImageNumber = Random.Range(1, 2);
        
        Debug.Log(BackgroundImageNumber);
        
        switch(BackgroundImageNumber)
        {
            case 1:
                BackgroundImage.sprite = Background1;
                break;
            case 2:
                BackgroundImage.sprite = Background2;
                break;
        }
    }
}

1 Answer

If you check the documentation for Unity's Random.Range(int,int) method: you will see that it is declared as public static int Range(int minInclusive, int maxExclusive), note that the second number is maxExclusive.

Therefore in order to get random value 1 or 2 you should use it like this: Random.Range(1,3)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.