【问题标题】:Random.Range only giving one outputRandom.Range 只给出一个输出
【发布时间】:2022-06-22 17:05:47
【问题描述】:

我有问题。每当我开始游戏时,我都会尝试随机化背景图像,但无论我重新滚动多少次,“BackgroundImageNumber”的输出始终为 1。提前致谢。

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

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    如果您查看 Unity 的 Random.Range(int,int) 方法的文档:https://docs.unity3d.com/ScriptReference/Random.Range.html,您会看到它被声明为 public static int Range(int minInclusive, int maxExclusive),请注意第二个数字是 maxExclusive .

    因此,为了获得随机值 1 或 2,您应该像这样使用它:Random.Range(1,3)

    【讨论】:

      猜你喜欢
      • 2020-01-12
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 2014-12-29
      • 2016-12-27
      • 1970-01-01
      相关资源
      最近更新 更多