Home > database >  Why it's not sending and moving each random drone from the list every 300ms?
Why it's not sending and moving each random drone from the list every 300ms?

Time:11-06

The manager script is attached to empty gameobject : I tried to use a loop in the coroutine but it's moving only one drone the rest are not moving.

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

It's moving only one but in the drones list there are 18 drones. I want to move random drone each time every 300ms.

The script DroneControl is attached to each drone :

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

CodePudding user response:

Your code is almost OK.

Problem is that you use WaitForSeconds(300).

300 means 300 seconds, i.e 5 minutes.

If you want to move a drone each 300ms use WaitForSeconds(0.3f)

  • Related