[英]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.
每当我开始游戏时,我都会尝试随机化背景图像,但无论我重新滚动多少次,“BackgroundImageNumber”的输出始终为 1。 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;
}
}
}
If you check the documentation for Unity's Random.Range(int,int) method: https://docs.unity3d.com/ScriptReference/Random.Range.html you will see that it is declared as public static int Range(int minInclusive, int maxExclusive)
, note that the second number is max Exclusive .如果您查看 Unity 的 Random.Range(int,int) 方法的文档: https ://docs.unity3d.com/ScriptReference/Random.Range.html,您会看到它被声明为
public static int Range(int minInclusive, int maxExclusive)
,请注意第二个数字是 max Exclusive 。
Therefore in order to get random value 1 or 2 you should use it like this: Random.Range(1,3)
因此,为了获得随机值 1 或 2,您应该像这样使用它:
Random.Range(1,3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.