Jak stworzyć kolejkę Queue w Unity?
Omówimy zagadnienie Queue na przykładzie kolejki samochodów ustawiających się po kawe.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Car : MonoBehaviour
{
public float MaxSpeed { get; private set; }
public float Speed { get; set; }
Rigidbody2D rb;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
void Start()
{
MaxSpeed = 5;
Speed = MaxSpeed;
}
void FixedUpdate()
{
rb.velocity = transform.right * Speed;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shop : MonoBehaviour
{
Queue<Car> carsQueue = new Queue<Car>();
Car activeCar;
bool isShopEmpty = true;
private void OnTriggerEnter2D(Collider2D collision)
{
Car car = collision.GetComponent<Car>();
carsQueue.Enqueue(car);
car.Speed = 0f;
}
private void OnTriggerExit2D(Collider2D collision)
{
activeCar.Speed = activeCar.MaxSpeed;
isShopEmpty = true;
}
void Update()
{
if (!isShopEmpty) return;
if (carsQueue.Count == 0) return;
activeCar = carsQueue.Dequeue();
isShopEmpty = false;
activeCar.Speed = 1f;
}
}