【问题标题】:Unity3D Pick random element from a list to show on clickUnity3D 从列表中选择随机元素以在点击时显示
【发布时间】:2018-08-04 20:09:08
【问题描述】:

又是我。你们真的很棒而且乐于助人,所以我只是希望你们能帮我最后一次!

我要做的是在单击按钮时从列表中选择一个随机元素。我知道这不是最难做的事情,但我仍然有点菜鸟,我似乎找到了关于数组的所有内容,我不确定数组是否是要追求的东西,因为我的元素列表可能会增长未来。

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

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);    
    }

}

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

谢谢!

【问题讨论】:

  • 您能说明一下您要从哪些项目列表中随机选择吗?现在看起来您正在构建一个布尔值列表 - 这些布尔值是您要从中随机选择的项目吗?如果是这样,一旦找到它们,你打算如何使用它们?你在哪里处理点击,你需要在哪里找到那个随机元素?

标签: c# unity3d


【解决方案1】:
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
  }

}

你可以随时提问

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-25
    • 2013-10-19
    • 2021-12-30
    • 2014-02-07
    • 2012-03-12
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多