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

Unity无人机管理协程为何无法每300ms随机移动列表内的无人机?

问题根因

  • 时间单位错误:WaitForSeconds的参数单位是秒,你填写的300表示间隔300秒(5分钟)才会执行下一次循环,所以你只能看到第一次随机选中的无人机移动,后续触发间隔太长无法观测到。你需要的300毫秒对应参数应为0.3f。
  • 循环次数受限:当前使用的for循环只会执行和无人机数量相等的18次就会终止协程,如果需要持续每300ms随机选中未启动的无人机,应该用无限循环。
  • 随机逻辑冗余:当前随机逻辑可能命中已经启动的无人机,此时本次等待不会启动新的无人机,相当于空跑。

修正后的代码

DronesManager.cs

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class DronesManager : MonoBehaviour
{
    private List<GameObject> idleDrones = new List<GameObject>();

    void Start()
    {
        // 初始化时把所有无人机加入待启动列表
        idleDrones = GameObject.FindGameObjectsWithTag("Drone").ToList();
        StartCoroutine(MoveDrone());
    }

    private IEnumerator MoveDrone()
    {
        // 只要还有未启动的无人机就一直循环
        while (idleDrones.Count > 0)
        {
            // 从未启动列表里随机选,保证每次都能启动新的
            var randomIndex = Random.Range(0, idleDrones.Count);
            var selectedDrone = idleDrones[randomIndex];
            var droneControl = selectedDrone.GetComponent<DroneControl>();
            
            droneControl.movingSpeed = 0.5f;
            droneControl.go = true;
            
            // 从待启动列表移除已经启动的无人机
            idleDrones.RemoveAt(randomIndex);
            
            // 等待300毫秒
            yield return new WaitForSeconds(0.3f);
        }
    }
}

如果需要所有无人机都启动后还继续随机选已经启动的无人机调整参数,可以把while条件改成true,去掉移除待启动列表的逻辑即可,原有的DroneControl脚本不需要修改。


内容的提问来源于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 04:36:08