コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】変数やプロパティにコンポーネントを自動で設定できる「Unity3D-ComponentAttribute」紹介

はじめに

「Unity3D-ComponentAttribute」を Unity プロジェクトに導入することで
変数やプロパティにコンポーネントを自動で設定できるようになります

使い方

using UnityEngine;

public class Example : MonoBehaviour
{
    [Component( "Main Camera" )]
    public Camera m_camera;
    [Component( "Directional Light" )]
    public Light m_light;

    [Component]
    public BoxCollider m_collider1;
    [Component( true, false )]
    public BoxCollider m_collider2;

    private void Awake()
    {
        this.LoadComponents();
    }
}

このように変数に Component 属性を付与して
Awake や Start で this.LoadComponents() を実行すると
該当するコンポーネントの参照が自動で設定されます

Component 属性の引数に文字列を渡した場合、
該当するゲームオブジェクトのコンポーネントの参照が設定されます

using UnityEngine;

public class Example : MonoBehaviour
{
    [Component( "Main Camera" )]
    public Camera Camera { get; set; }
    [Component( "Directional Light" )]
    public Light Light { get; set; }

    [Component]
    public BoxCollider Collider1 { get; set; }
    [Component( true, false )]
    public BoxCollider Collider2 { get; set; }

    private void Awake()
    {
        this.LoadComponents();
    }
}

Component 属性はプロパティに対しても使用できます

関連記事