Queue w Unity C#

Jak stworzyć kolejkę Queue w Unity?
Omówimy zagadnienie Queue na przykładzie kolejki samochodów ustawiających się do myjni.
Pod filmem możecie pobrać paczki do projektu.

using UnityEngine;

public class Car : MonoBehaviour
{
    public float MaxSpeed { get; private set; }
    public float Speed { get; set; }
    Rigidbody rb;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        MaxSpeed = 5;
        Speed = MaxSpeed;
    }

    void FixedUpdate()
    {
        rb.velocity = Vector3.forward * Speed;
    }
}
using System.Collections.Generic;
using UnityEngine;

public class CarWash : MonoBehaviour
{
    Queue<Car> carsQueue = new Queue<Car>();
    Car activeCar;
    bool isCarWashEmpty = true;

    private void OnTriggerEnter(Collider other)
    {
        Car car = other.GetComponent<Car>();
        carsQueue.Enqueue(car);
        car.Speed = 0f;
    }

    private void OnTriggerExit(Collider other)
    {
        activeCar.Speed = activeCar.MaxSpeed;
        isCarWashEmpty = true;
        activeCar.GetComponent<Renderer>().material.color = Color.cyan;
    }

    void Update()
    {
        if(carsQueue.Count > 0 && isCarWashEmpty)
        {
            activeCar = carsQueue.Dequeue();
            isCarWashEmpty=false;
            activeCar.Speed = 0.5f;
        }
    }
}

Kursy GameDev Unity

Scroll to Top