using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DronesManager : MonoBehaviour
{
private List<GameObject> drones = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
drones = GameObject.FindGameObjectsWithTag("Drone").ToList();
StartCoroutine(MoveDrone());
}
// Update is called once per frame
void Update()
{
}
private IEnumerator MoveDrone()
{
for (int i = 0; i < drones.Count; i++)
{
var drone = drones[Random.Range(0, drones.Count)];
if (drone.GetComponent<DroneControl>().go == false)
{
drone.GetComponent<DroneControl>().movingSpeed = 0.5f;
drone.GetComponent<DroneControl>().go = true;
}
yield return new WaitForSeconds(0.3f);
}
}
}我翻阅了协同线中的无人机列表,但每次都有一些无人驾驶飞机停留不动。我想做的是循环浏览无人机列表并移动每个无人机,但每次都随机地从列表中移出一个。直到所有的无人机都在移动。
问题是因为它是随机的,有些无人驾驶飞机呆在那里,从来没有被摘过。
附在每个无人机上并移动它的脚本:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DroneControl : MonoBehaviour
{
public float movingSpeed;
public bool go = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(go)
{
transform.position -= transform.forward * movingSpeed * Time.deltaTime;
}
}
}这就是我试过的:
不过,还是有一些无人驾驶飞机呆在原地不动。
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DronesManager : MonoBehaviour
{
private List<GameObject> drones = new List<GameObject>();
private static System.Random rnd = new System.Random();
// Start is called before the first frame update
void Start()
{
drones = GameObject.FindGameObjectsWithTag("Drone").ToList();
StartCoroutine(MoveDrone());
}
// Update is called once per frame
void Update()
{
}
private IEnumerator MoveDrone()
{
for (int i = 0; i < drones.Count; i++)
{
var numbers = new List<int>(Enumerable.Range(0, drones.Count));
var droneIndices = numbers.OrderBy(a => rnd.Next()).ToList();
var drone = drones[droneIndices[i]];
if (drone.GetComponent<DroneControl>().go == false)
{
drone.GetComponent<DroneControl>().movingSpeed = 0.5f;
drone.GetComponent<DroneControl>().go = true;
}
yield return new WaitForSeconds(0.3f);
}
}
}发布于 2021-11-06 17:53:45
您每次都使用新的随机值。它们很可能会重复。解决办法是跟踪移动的索引,并将该值排除在可能的索引数组中。或者,只需使用索引数组0-n并对它们进行洗牌,然后在它们出现时使用它们。
替换
var drone = drones[Random.Range(0, drones.Count)];使用
private static System.Random rnd = new System.Random();
var numbers = new List<int>(Enumerable.Range(0, drones.Count));
var droneIndices = numbers.OrderBy(a => rnd.Next()).ToList();
var drone = drones[droneIndices[i]];https://stackoverflow.com/questions/69866319
复制相似问题