今回はUnity(C#スクリプト)でContainsを利用して「特定の文字列」または「特定の要素」があるのかを調べる方法のメモです。
はじめに
UnityというよりはC#のプログラムメモ的な感じです。
簡単なスクリプトの例
実際に簡単なスクリプトで見ていきます。
まずはHierarchyで右クリック、CreateEmptyで空のオブジェクトを追加します。

名前をsampleに変更、オブジェクトにスクリプトをアタッチします。

文字列の検索
まずは文字列があるかどうかのサンプルのスクリプトです。
using UnityEngine; public class ContainsSample : MonoBehaviour { private void Start() { string src = "ABCDEFG"; string target = "CDE"; if (src.Contains(target)) Debug.Log(target + " is Found"); else Debug.Log(target " is NotFound"); } }
ターゲットとなる文字列「CDE」が「ABCDEFG」内にあるかどうか探しています。ターゲット文字列をパラメータに、見つかればtrueを返します。
これを実行すると下記の様に。

特定の要素の検索
Unityで利用する場合はコチラの方が利用機会が多いかも。要素の検索です。
using System.Collections.Generic; using UnityEngine; public class ContainsSample : MonoBehaviour { private void Start() { int[] src = { 1, 2, 3, 4, 5 }; var srclist = new List<int>(); srclist.AddRange(src); int target = 3; if (srclist.Contains(target)) Debug.Log(target + " is Found"); else Debug.Log(target + " is NotFound"); } }
int型の配列「1,2,3,4,5」の中に「3」があるかを検索しています。Vector2型にすると座標検索とかに使えそうですね。
実行すると下記の様な感じに。
