using System;
using UnityEngine;
/// <summary>
/// 系统函数扩展
/// </summary>
public static class Extension
{
//Unity内置的GetOrAddComponent方法对自定义的类型无效,因此扩展
public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
{
if (gameObject)
{
T t = gameObject.GetComponent<T>();
if (t == null)
{
t = gameObject.AddComponent<T>();
}
return t;
}
return null;
}
public static T FindInParents<T>(this GameObject go) where T : Component
{
if (go == null) return null;
var comp = go.GetComponent<T>();
if (comp != null)
return comp;
var t = go.transform.parent;
while (t != null && comp == null)
{
comp = t.gameObject.GetComponent<T>();
t = t.parent;
}
return comp;
}
public static void TryInvoke<T>(this Action<T> action, T param)
{
if (action == null) return;
try
{
action(param);
}
catch (Exception ex)
{
throw ex;
}
}
public static void TryInvoke(this Action action)
{
if (action == null) return;
try
{
action();
}
catch (Exception ex)
{
throw ex;
}
}
}
系统类型方法扩展Extension
于 2023-05-30 11:53:01 首次发布