c# - 随机选择图像以在 c# unity 中的随机按钮上显示

标签 c# image button random unity3d

我想显示 4 张随机图像,其中一张图像是正确的图像。所以我从“correct_caps”文件夹中选择了 1 个随机图像,并从另一个文件夹中选择了 3 个。现在,我想选择随机图像变量来显示该图像,以便我的正确图像始终改变其位置。

using UnityEngine;
 using UnityEngine.SceneManagement;
 using UnityEngine.UI;
 using UnityEngine.EventSystems;



 public class NewBehaviourScript : MonoBehaviour
  {
 public Image art1;
 public Image art2;
 public Image art3;
 public Image art4;


 public int x;
 public int x1;
 public int x2;
 public int x3;

 public string s;
 public string path;
 public string path1;
 public string path2;
 public string path3;
 public string path4;

 public int cl;
 public int i;


 void Start()
 {


     //selection of correct letter
     cl = Random.Range(1, 26);

     path1 = "Capital Letters/correct_caps/" + cl;
     path = "Capital Letters/" + cl;
     Debug.Log("Load path is " + path1);


     x1 = Random.Range(1, 5);
     path2 = path + "/" + x1;



     x2 = Random.Range(1, 5);
     path3 = path + "/" + x2;
     i = 0;
     while (i == 0)
     {
         if (x1 == x2)
         {

             x2 = Random.Range(1, 5);
             path3 = path + "/" + x2;
             Debug.Log("Load path3 is " + path3);

         }
         else
         {

             Debug.Log("Load path3 is " + path3);
             i++;
         }
     }




     x3 = Random.Range(1, 5);
     path4 = path + "/" + x3;

     i = 0;
     while (i == 0)
     {
         if (x1 == x3 || x2 == x3)
         {
             x3 = Random.Range(1, 5);
             path4 = path + "/" + x3;
             Debug.Log("Load path4 is " + path4);
         }
         else
         {

             Debug.Log("Load path4 is " + path4);
             i++;
         }
     }

  //here I displayed images . But, I want to select art,art1,art2,art3 randomly.

   art.sprite = Resources.Load<Sprite>(path1) as Sprite; 
    art1.sprite = Resources.Load<Sprite>(path2) as Sprite;
     art2.sprite = Resources.Load<Sprite>(path3) as Sprite;
    art3.sprite = Resources.Load<Sprite>(path4) as Sprite;  
 }    

 }

最佳答案

在 1-4 之间取一个随机数,然后使用 if 语句。

 Random random = new Random();
 int randomNumber = random.Next(0, 5);
 if (randomNumber ==1)
 {
      art.sprite = Resources.Load<Sprite>(path1) as Sprite; 
 }
 if (randomNumber ==2)
 {
      art1.sprite = Resources.Load<Sprite>(path2) as Sprite; 
 }
 if (randomNumber ==3)
 {
      art2.sprite = Resources.Load<Sprite>(path3) as Sprite; 
 }
 if (randomNumber ==4)
 {
      art3.sprite = Resources.Load<Sprite>(path4) as Sprite; 
 }

关于c# - 随机选择图像以在 c# unity 中的随机按钮上显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36555103/

相关文章:

C# & SQL Server : how to Insert DBNull. 如果字符串值为空,命令参数中的值?

c# - Task.Delay 的同步上下文

java - 从名称和索引中选择图像

windows - 如何更改任务栏上按钮的顺序?

jquery - grails 中带有 2 个按钮的 div

winforms - 在 WinForms 中将按钮添加到 ListView 中

c# - 绑定(bind)和x :Bind problems with TwoWay mode

c# - 极慢的 WatiN.Core.Document.FileUpload 集

html - 在 JSP 中加载 img

image - 在没有文本和图像重叠的情况下找到文档上的最佳图章位置