在Unity中如何通过Random.Range从Resources/Images目录随机加载图片纹理
问题核心错误点
- 路径拼接错误:代码中
"Images/imageIndex"是固定字符串,Unity会尝试加载Resources/Images下名为imageIndex的资源,而非使用imageIndex变量的实际值,你需要将变量值拼接到路径字符串中。 - 随机数范围错误:Unity中
Random.Range针对整数参数的重载为左闭右开规则,即包含最小值、不包含最大值,你设置上限为images.Count - 1会导致永远无法随机到最后一个索引值。 - 逻辑冗余:你当前定义的
images列表存储的字符串未被实际使用,你的图片命名为0/1/2,与索引直接对应,可按需简化逻辑。
修正后可运行代码
private int imageIndex; public GameObject rawImage; Texture2D myTexture; // 和Images文件夹下的图片总数量保持一致即可 private const int IMAGE_TOTAL_COUNT = 3; void Start() { // 随机范围左闭右开,上限直接写总数量即可覆盖0、1、2三个索引 imageIndex = Random.Range(0, IMAGE_TOTAL_COUNT); // 字符串拼接得到正确路径,比如随机到0时路径就是"Images/0" myTexture = Resources.Load($"Images/{imageIndex}") as Texture2D; // 如果你的C#版本不支持字符串插值,替换为下面的写法即可 // myTexture = Resources.Load("Images/" + imageIndex.ToString()) as Texture2D; rawImage.GetComponent<RawImage>().texture = myTexture; }
如果你需要保留原有的images列表做后续扩展,只需调整路径取值逻辑即可:
// 把列表内容改成和你的图片名对应即可 private List<string> images = new List<string>(){"0", "1", "2"}; private int imageIndex; public GameObject rawImage; Texture2D myTexture; void Start() { imageIndex = Random.Range(0, images.Count); myTexture = Resources.Load($"Images/{images[imageIndex]}") as Texture2D; rawImage.GetComponent<RawImage>().texture = myTexture; }
内容的提问来源于stack exchange,提问作者acemi
相关产品推荐
相关产品推荐

