[英]Unity3D Pick random element from a list to show on click
It's me again. 又是我。 You guys have been really amazing and helpful so I was just hoping you'd help me one last time!
你们真的很棒而且乐于助人,所以我只是希望您能在上一次帮助我!
What I'm trying to do is to pick a random element from a list when a button is clicked. 我想做的是单击按钮时从列表中选择一个随机元素。 I know its not the hardest thing to do, but I'm still kinda noob and everything I seem to find its about arrays and I'm not sure an array is the thing to go after, since my list of elements could possibly grow in the future.
我知道这不是最难的事情,但是我还是有点菜,而且我似乎也能找到有关数组的一切,而且我不确定要处理的事情是数组,因为我的元素列表可能会增加未来。
So far, I have this code for my listing: 到目前为止,我的清单已包含以下代码:
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);
}
}
The whole point of the random picking, is to show a different image ("Frame") each time the button is pressed. 每次随机选择的重点是每次按下按钮时都显示不同的图像(“帧”)。
Thanks! 谢谢!
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
}
} }
You can ask question whenever you want 您可以随时问问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.