今回はUnityと言うか少しプログラム的なメモです。スタック(stack)とキュー(queue)の基本と違いについてです。
はじめに
stackとqueueの基本を見ていきます。
stackとは
stackとは後入れ先出し(LIFO)の可変サイズのコレクションです。
机の上に本を積み上げるイメージで、下記の様にデータは上に積み上げられ、取り出すときも上から順番です。

queueとは
queueとは先入れ先出し(FIFO)の可変サイズのコレクションです。
順番待ちのイメージで、下記の様に早く来た順にデータが並び、古いデータから順に取り出します。

stackやqueueは多くのプログラミング言語に存在し、もちろんUnityのC#にもあります。実際にどのように利用するのか簡単に見ていきます。
簡単なスクリプト例
簡単なスクリプトを作成して動作を確認してみます。
stack
空のオブジェクトを追加してStackと言う名前でスクリプトをアタッチ。

スクリプトの中身は下記に変更します。Pushはデータの追加。Popはデータを削除して取り出し、Peekはデータを削除せずに取り出しです。
using System.Collections.Generic; using UnityEngine; public class Stack : MonoBehaviour { Stack<int> stack = new Stack<int>(); void Start() { stack.Push(1); stack.Push(2); stack.Push(3); int pop = stack.Pop(); Debug.Log("pop: " + pop); int peek = stack.Peek(); Debug.Log("Peek: " + peek); stack.Clear(); int count = stack.Count; Debug.Log("Count: " + count); } }
実行すると下記の様に。最後に追加された「3」が取り出されます。

より詳しい内容は下記にて。
queue
空のオブジェクトを追加してQueueと言う名前でスクリプトをアタッチ。

スクリプトの中身は下記に変更します。Enqueueはデータの追加。dequeueはデータを削除して取り出し、Peekはデータを削除せずに取り出しです。
using System.Collections.Generic; using UnityEngine; public class Queue : MonoBehaviour { private Queue<int> queue = new Queue<int>(); void Start() { queue.Enqueue(0); queue.Enqueue(1); queue.Enqueue(2); int dequeue = queue.Dequeue(); Debug.Log("dequeue: " + dequeue); int peek = queue.Peek(); Debug.Log("peek: " + peek); queue.Clear(); int count = queue.Count; Debug.Log("Count: " + count); } }
実行すると下記の様に。最初に追加した「0」が取り出されます。

より詳しい内容は下記にて。