【问题标题】:Instantiate 4 prefabs at 4 locations, shuffled, Unity Engine C#在 4 个位置实例化 4 个预制件,混洗,Unity Engine C#
【发布时间】:2017-12-21 02:34:27
【问题描述】:

我有 4 个平台,我在 4 个位置进行实例化。我想要的是每次都对平台进行洗牌。到目前为止我的代码:

using UnityEngine;

public class PlatformCreator : MonoBehaviour {

 public GameObject[] platforms;
 public Transform[] points;

 private void Start()
 {

     for (int i = 0; i < points.Length; i++)
     {
         Instantiate(platforms[i], points[i].position, Quaternion.identity);
     }
 }

}

例如,平台现在总是以相同的顺序生成 - 粉色、黄色、蓝色、紫色

我希望它们每次都以不同的顺序生成,例如 - 黄色、蓝色、紫色、粉红色。我尝试使用 random.range 创建一个 int 索引,但我搞砸了

【问题讨论】:

  • 您可以在 for 循环中使用 int x = Random.Range(0,points.Length) 然后再使用 points[x].position 吗?

标签: c# unity3d instantiation


【解决方案1】:

您可以将点添加到列表而不是数组,这将帮助您“打乱”这些值。从This SO 帖子中获取随机播放功能,您可以执行以下操作:

public class PlatformCreator : MonoBehaviour {

 public GameObject[] platforms;
 public List<Transform> points;

 private Random rng; 

 public void Shuffle<T>(this IList<T> list)  
 {  
    int n = list.Count;  
    while (n > 1) {  
    n--;  
    int k = rng.Next(n + 1);  
    T value = list[k];  
    list[k] = list[n];  
    list[n] = value;  
    }  
 }

 private void Start()
 {
    rng = new Random(); 
    points.Shuffle();
    for (int i = 0; i < points.Count; i++)
    {
        Instantiate(platforms[i], points[i].position, Quaternion.identity);
    }
 }
}

【讨论】:

  • 不幸的是它不起作用,因为 points.Length 属性不能与列表一起使用。也许我可以尝试使用 .Count (points.Count)?与 int k = rng.Next() 相同的问题,我无法使用 Next(),收到错误。
  • 是的,对不起。列表使用计数,而不是长度。更新了答案。
  • 你能告诉我错误是什么吗?除非您发布,否则我无法知道。
  • 它有效,我想我会多看看这种洗牌方法,它引起了我的注意。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-04
  • 2014-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
相关资源
最近更新 更多