Skip to content

Instantly share code, notes, and snippets.

@baba-s
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save baba-s/9305068 to your computer and use it in GitHub Desktop.

Select an option

Save baba-s/9305068 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">ゲームオブジェクト</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">ゲームオブジェクト</param>
/// <param name="type">コンポーネントの型</param>
/// <returns>指定されたコンポーネント</returns>
public static Component SafeGetComponent(this GameObject gameObject, string type)
{
return
gameObject.GetComponent(type) ??
gameObject.AddComponent(type);
}
/// <summary>
/// 指定されたコンポーネントを安全に取得します
/// </summary>
/// <param name="gameObject">ゲームオブジェクト</param>
/// <param name="type">コンポーネントの型</param>
/// <returns>指定されたコンポーネント</returns>
public static Component SafeGetComponent(this GameObject gameObject, Type type)
{
return
gameObject.GetComponent(type) ??
gameObject.AddComponent(type);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment