Unity3D从列表中选择随机元素以在单击时显示

时间:2018-07-31 15:57:32

标签: c# unity3d

又是我。你们真的很棒而且很有帮助,所以我只是希望您能在上一次帮助我!

我想做的是单击按钮时从列表中选择一个随机元素。我知道这不是最难的事情,但是我还是有点菜,而且我似乎也能找到有关数组的一切,而且我不确定要处理的事情是数组,因为我的元素列表可能会增加未来。

到目前为止,我的列表中包含以下代码:

using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class FrameSelector : MonoBehaviour
{
    void Start()
    {
            List<bool> frame = new List<bool>();
            frame.Add(GameObject.Find("Frame1").GetComponent<Image>().enabled = true);
            frame.Add(GameObject.Find("Frame2").GetComponent<Image>().enabled = true);
            frame.Add(GameObject.Find("Frame3").GetComponent<Image>().enabled = true);
            frame.Add(GameObject.Find("Frame4").GetComponent<Image>().enabled = true);    
    }

}

每次随机选择的重点是每次按下按钮时都显示不同的图像(“帧”)。

谢谢!

1 个答案:

答案 0 :(得分:0)

using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class FrameSelector : MonoBehaviour
{
   List<bool> frame; //make list field not local variable to reuse
   System.Random rand;
   void Start()
   {
        rand = new System.Rand();
        frame = new List<bool>();
        frame.Add(GameObject.Find("Frame1").GetComponent<Image>().enabled = true);
        frame.Add(GameObject.Find("Frame2").GetComponent<Image>().enabled = true);
        frame.Add(GameObject.Find("Frame3").GetComponent<Image>().enabled = true);
        frame.Add(GameObject.Find("Frame4").GetComponent<Image>().enabled = true);    
    }
  void GetRandomObject() // call on click making it public and assigning in inspector 
  {
     int randomNumber = rnd.Next(0,frame.Length-1); //length-1 for not throwing 
//indexError
     //do what you want with your randomNumber
  }

}

您可以随时问问题