Skip to content

Instantly share code, notes, and snippets.

@baba-s
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baba-s/9678433 to your computer and use it in GitHub Desktop.
Save baba-s/9678433 to your computer and use it in GitHub Desktop.
using System;
using UnityEngine;
/// <summary>
/// GameObject型の拡張メソッドを管理するクラス
/// </summary>
public static partial class GameObjectExtensions
{
/// <summary>
/// コンポーネントを取得します。コンポーネントが存在しなければ追加してから取得します
/// </summary>
/// <typeparam name="T">取得するコンポーネントの型</typeparam>
/// <param name="gameObject">GameObject型のインスタンス</param>
/// <returns>コンポーネント</returns>
public static T SafeGetComponent<T>(this GameObject gameObject) where T : Component
{
return gameObject.GetComponent<T>() ?? gameObject.AddComponent<T>();
}
/// <summary>
/// コンポーネントを取得します。コンポーネントが存在しなければ追加してから取得します
/// </summary>
/// <param name="gameObject">GameObject型のインスタンス</param>
/// <param name="className">取得するコンポーネントの名前</param>
/// <returns>コンポーネント</returns>
public static Component SafeGetComponent(this GameObject gameObject, string className)
{
return gameObject.GetComponent(className) ?? gameObject.AddComponent(className);
}
/// <summary>
/// コンポーネントを取得します。コンポーネントが存在しなければ追加してから取得します
/// </summary>
/// <param name="gameObject">GameObject型のインスタンス</param>
/// <param name="componentType">取得するコンポーネントの種類</param>
/// <returns>コンポーネント</returns>
public static Component SafeGetComponent(this GameObject gameObject, Type componentType)
{
return gameObject.GetComponent(componentType) ?? gameObject.AddComponent(componentType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment