【Unity】enumでtagのように管理するスクリプトを作成する


Unityのtag管理

Unityのtag管理ではTagManager.assetというファイルで管理され, Git管理する際, 違うブランチで同時にtagを変更してしまうと, コンフリクトを起こしてしまうなどの問題があります.
そこで, enumでtagのように管理をするスクリプトを作成します.


1. GameDataType.csを作成します.

GameDataType.cs
using UnityEngine;
namespace kkkkoyo.basic
{
    public class GameDataType : MonoBehaviour
    {
        public DataType dataType = DataType.None;
    }
    public enum DataType : int
    {
        None,
        CubeA,
        CubeB
    }
}

2. 2つのキューブにGameDataType.csをアタッチして, 各DataTypeを設定します.

3. Player.csを作成しPlayerオブジェクトにアタッチします.

Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using kkkkoyo.basic;//追加
public class Player : MonoBehaviour
{

    void OnTriggerEnter(Collider collider)
    {
        GameDataType componentType = collider.gameObject.GetComponent<GameDataType>();

        if (componentType == null)
        {
          /*
          GameDataType.csがコンポーネントに追加されてない
          オブジェクトと接触した際のエラー回避
          */
          return;          
        }
        if (componentType.dataType == DataType.CubeA)
        {
            Debug.Log("CubeAと接触");
        }
        else if (componentType.dataType == DataType.CubeB)
        {
            Debug.Log("CubeBと接触");
        }
    }
}

これで完成です.

 


おわりに

UnityのtagはTagManager.assetとしてプロジェクト内に1つのファイルとして管理されており, 大きいプロジェクトになると管理が難しくなります.

GameDataType.csのようにenumでtagのように扱うスクリプトを複数作成することにより, tagを用いるより管理が容易になります.