Unity随机改变图像
Unity randomly change image
我正在使用 Unity。我想随机更改图像,可能通过按下按钮或触发事件。
我可以想到这样的解决方案:
public Image randomImage;
public Sprite s0;
public Sprite s1;
public Sprite s2;
public Sprite s3;
public Sprite[] images;
void Start(){
images = new Sprite[4];
images [0] = s0;
images [1] = s1;
images [2] = s2;
images [3] = s3;
}
void changeImage(){
Random rnd = new Random();
int num = rnd.Next(0, 4);
randomImage <Image> ().sprite = images[num];
}
然后我可以把我要换的sprite拖到randomImage中,拖四个image到s0,s1,s2,s3。
但是,我要选择的图像数量远大于 4 个,可能是 20 个。我不知道是否有更聪明的方法来代替创建 20 个变量并将 20 个图像拖入其中。
谢谢你。
您需要使用 UnityEngine.Random.Range
。而已。您不必创建它的新实例。
由于数组从0
开始,将0
传递给第一个参数,将数组长度传递给第二个参数。第二个参数是唯一的,所以你不会得到超出范围的异常。
不需要randomImage <Image> ()
因为randomImage
已经是一个Image(public Image randomImage;
)。如果 randomImage
是 GameObject 或任何其他类型,你应该这样做。
public Image randomImage;
public Sprite s0;
public Sprite s1;
public Sprite s2;
public Sprite s3;
public Sprite[] images;
void Start()
{
images = new Sprite[4];
images[0] = s0;
images[1] = s1;
images[2] = s2;
images[3] = s3;
}
void changeImage()
{
int num = UnityEngine.Random.Range(0, images.Length);
randomImage.sprite = images[num];
}
我正在使用 Unity。我想随机更改图像,可能通过按下按钮或触发事件。
我可以想到这样的解决方案:
public Image randomImage;
public Sprite s0;
public Sprite s1;
public Sprite s2;
public Sprite s3;
public Sprite[] images;
void Start(){
images = new Sprite[4];
images [0] = s0;
images [1] = s1;
images [2] = s2;
images [3] = s3;
}
void changeImage(){
Random rnd = new Random();
int num = rnd.Next(0, 4);
randomImage <Image> ().sprite = images[num];
}
然后我可以把我要换的sprite拖到randomImage中,拖四个image到s0,s1,s2,s3。 但是,我要选择的图像数量远大于 4 个,可能是 20 个。我不知道是否有更聪明的方法来代替创建 20 个变量并将 20 个图像拖入其中。 谢谢你。
您需要使用 UnityEngine.Random.Range
。而已。您不必创建它的新实例。
由于数组从0
开始,将0
传递给第一个参数,将数组长度传递给第二个参数。第二个参数是唯一的,所以你不会得到超出范围的异常。
不需要randomImage <Image> ()
因为randomImage
已经是一个Image(public Image randomImage;
)。如果 randomImage
是 GameObject 或任何其他类型,你应该这样做。
public Image randomImage;
public Sprite s0;
public Sprite s1;
public Sprite s2;
public Sprite s3;
public Sprite[] images;
void Start()
{
images = new Sprite[4];
images[0] = s0;
images[1] = s1;
images[2] = s2;
images[3] = s3;
}
void changeImage()
{
int num = UnityEngine.Random.Range(0, images.Length);
randomImage.sprite = images[num];
}