LoginSignup
1
1

More than 3 years have passed since last update.

UnityでListの中身を表示する

Posted at

はじめに

初投稿です。よろしくお願いします。

Unity2019.2.0f1
Windows10 64bit

概要

ボタンを押してListに情報を入れ、Consoleに中身を表示する機能を作成します。
今回はenumと組み合わせてListに情報を入れていきます。
MIRS_Test-SampleScene-PC_-Mac-_-Linux-Standalone-Unity-2019.2.gif

作成手順

前提

Listやenumについて詳しく書いている方がたくさんいらっしゃるので、ここでは簡単な使い方のみ列挙します。

- List

以下のようにListを宣言します。

sample.cs
private List<"型名"> "List名" = new List<"型名">();

Listへの入力は次のように行います。

sample.cs
"リスト名".Add("オブジェクト名"."列挙子");
  • enum

以下のようにenumを定義します。

sample.cs
public enum "オブジェクト名"
{      
    "列挙子1",
    "列挙子2",
    "列挙子3",
    "列挙子4"
}

非同期処理

このままではリストの中身が一気に表示されてしまうため、非同期処理を用いて2秒ごとに1つずつ表示するようにします。また、リストの中身はToString()を用いてString型にします。

sample.cs
async void "関数名"()
{
    foreach ("オブジェクト名" A in "リスト名")
    {
        Debug.Log(A.ToString());
        await Task.Delay(2000);    //遅延処理
    }
}

ソースコード

以下が全体のソースコードです。それぞれのボタンの関数を当てはめることで実際に動かすことができます。

sample.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;

public class sample : MonoBehaviour
{
    private List<Direction> Dirlist = new List<Direction>();     //Listの宣言

    public enum Direction
    {      //enumの定義
        Straight,
        Back,
        Left,
        Right
    }

    public void StraightButton()
    {
        Dirlist.Add(Direction.Straight);
    }

    public void BackButton()
    {
        Dirlist.Add(Direction.Back);
    }

    public void RightButton()
    {
        Dirlist.Add(Direction.Right);
    }

    public void LeftButton()
    {
        Dirlist.Add(Direction.Left);
    }

    public void SearchButton()
    {
        Search();
    }

    async void Search()
    {
        foreach (Direction dir in Dirlist)
        {
            Debug.Log(dir.ToString());
            await Task.Delay(2000);
        }
    }
}

おわりに

いかがでしたでしょうか。Listやenumを取り入れれば、可能性の幅はもっと広がると思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1