LoginSignup
4
4

More than 5 years have passed since last update.

[Unity2D]スマートフォン向けタッチされたオブジェクト一覧取得

Posted at

はじめに

Unity のタッチ処理第2弾です。
今回は指定オブジェクト名一覧を取得する処理です。
「特定オブジェクトに一括で何かをしたいとき」
とかに使えるかと思います。

実装

TouchManager.cs
/// <summary>
/// タッチされた該当オブジェクトの一覧を取得.
/// </summary>
/// <param name="aName">オブジェクト名</param>
/// <param name="aCompMatch">true = 完全一致</param>
/// <param name="aCompMatch">false = 部分一致</param>
/// <returns>オブジェクト一覧</returns>
public static GameObject[] GetTouchObjectAll(string aName, bool aCompMatch=true)
{
    List<GameObject> list = new List<GameObject>();
    for (int i = 0; i < Input.touchCount; ++i)
    {
        Touch touch = Input.touches[i];
        if (touch.phase == TouchPhase.Began)
        {
            Vector3 pos = Camera.main.ScreenToWorldPoint(touch.position);
            Collider2D[] colliders = Physics2D.OverlapPointAll(pos);
            foreach (Collider2D collider in colliders)
            {
                if ((aCompMatch && collider.gameObject.name.Equals(aName)) || 
                    (!aCompMatch && 0 <= collider.gameObject.name.IndexOf(aName)))
                {
                    Debug.Log("touch object name : " + collider.gameObject.name);
                    list.Add(collider.gameObject);
                }
            }
        }
    }
    return list.ToArray();
}

使い方

Main.cs
/// <summary>
/// 更新.
/// </summary>
void Update()
{
    GameObject[] array = TouchManager.GetTouchObjectAll("Enemy");
    foreach(GameObject obj in array)
    {
        // 完全一致時のタッチされた時の処理.
    }

    array = TouchManager.GetTouchObjectAll("Enemy", false);
    foreach(GameObject obj in array)
    {
        // 部分一致時のタッチされた時の処理.
    }
}

最後に

これでタッチされたオブジェクト一覧を取得できます。
Hierarchy上の名前で判断するので命名規則とかにはお気をつけを。

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