You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity开发中随机触发无人机移动时部分设备静止问题如何解决

问题根本原因
  • 第一版代码问题:循环总次数等于无人机总数,但每次随机选取时没有排除已经启动的无人机,极大概率出现重复选中已启动设备的情况,最终循环走完后仍有部分无人机从未被选中,保持静止。
  • 第二版代码问题:随机打乱索引的逻辑写在了for循环内部,每一轮循环都会重新生成一个全新的乱序列表,再取当前轮次i对应的索引,仍然会出现不同轮次取到相同索引的问题,无法保证所有无人机都被选中一次。
正确实现方案

核心逻辑:协程开始时一次性生成全局唯一的乱序索引序列,再按序列逐个启动无人机,保证每台无人机被选中且仅被选中一次,完全满足间隔0.3秒随机顺序逐台启动的需求。

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

    void Start()
    {
        drones = GameObject.FindGameObjectsWithTag("Drone").ToList();
        StartCoroutine(MoveDrone());
    }

    private IEnumerator MoveDrone()
    {
        // 一次性生成全局不重复的乱序索引列表,放在for循环外部
        var droneIndices = Enumerable.Range(0, drones.Count).OrderBy(a => rnd.Next()).ToList();
        
        for (int i = 0; i < droneIndices.Count; i++)
        {
            var drone = drones[droneIndices[i]];
            var droneControl = drone.GetComponent<DroneControl>();
            droneControl.movingSpeed = 0.5f;
            droneControl.go = true;
            
            yield return new WaitForSeconds(0.3f);
        }
    }
}

额外优化建议:如果无人机数量较多,可提前在Start方法中把所有DroneControl组件缓存到列表里,避免运行时反复调用GetComponent,进一步提升性能。

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:45:07