0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Unity]Switch文_to_Delegate

Last updated at Posted at 2019-10-29

はじめに

〇YouTubeでUnity Japanの安原 祐二さんが解説している、[part3-プッシュとプル]という動画で、Switch文をdelegateに変えることでスッキリした文章になっていたので、理解するべく個人の記事にまとめました。

〇動画で、紹介されていたところ ↓↓
delegate_to_switch.png
[参照]https://www.youtube.com/watch?v=HwD7npYb9_k

まず、コード

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SwitchToDelegate : MonoBehaviour
{
    void Start()
    {
	// ステージにギミックをランダムに発生させる
	funcGimmick[UnityEngine.Random.Range(0, funcGimmick.Length - 1)];
    }

    private delegate int funcDelegate(Rigidbody[] rb, int index, int create_num);

    private static Dictionary<GimmickType,funcDelegate> funcGimmick = new Dictionary<GimmickType, funcDelegate>
    {
        {GimmickType.Fall, 	FallGimmick },
        {GimmickType.BurnOut, 	BurnOutGimmick },
    };
    private static int FallGimmick(Rigidbody[] rb, int index, int create_num)
    {
        // ステージが落ちる
	return 0;
    }
    private static int BurnOutGimmick(Rigidbody[] rb, int index, int create_num)
    {
        // ステージが跳ねる
	return 0;
    }
}

public enum GimmickType
{
    Fall,
    BurnOut
}

〇このコードは、ステージにランダムでギミックを発生させる処理を書いたときに使ってみたのでその時のコードから切り取ってます。

利用するときに

〇Enum型をDictionaryのKeyにしているため、
funcGimmick[GimmickType.Fall]
のように呼ぶことができる。

〇型省略
private static Dictionary funcGimmick = new Dictionary ⇒
var funcGimmick = new Dictionary
{
//すっきりする
}

〇速度面
自身では検証していないが、調べたところ
C#では、列挙型をキーにしたDictionaryは
.NET4.6以前:int型のキーと比べて5倍ほど遅い
.NET4.6以降:int型のキーと比べて差がない
[参照]https://qiita.com/goropocha/items/9c58d4f163c1e409a3fd

おわりに

勉強になった( )
追記:最初、限定公開で個人的なメモにしてたのでいろいろ雑

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?