Unity如何一行完成GetComponent获取与空值判断以简化冗余代码
代码简化方案
方案1:C# 模式匹配写法(适配Unity 2018及以上版本,完全符合你期望的语法效果)
利用C# 7.0引入的模式匹配语法,可以直接在if判断中完成组件获取、非空判断、变量声明三个步骤,变量作用域仅限定在if代码块内:
// 单个组件判断写法 if (gameObject.GetComponent<MyComponent>() is MyComponent myComponent) { // 此处可直接使用非空的myComponent }
对应你的多组件分支场景可以简化为:
if (gameObject.GetComponent<ComponentOne>() is ComponentOne componentOne) { // ComponentOne逻辑 return; } if (gameObject.GetComponent<ComponentTwo>() is ComponentTwo componentTwo) { // ComponentTwo逻辑 return; } if (gameObject.GetComponent<ComponentThree>() is ComponentThree componentThree) { // ComponentThree逻辑 return; }
方案2:使用TryGetComponent(适配Unity 2019及以上版本,性能更优)
Unity 2019之后原生提供了TryGetComponent方法,相比直接GetComponent后判空的性能更好,不会产生额外的空对象GC开销:
// 单个组件判断写法 if (gameObject.TryGetComponent(out MyComponent myComponent)) { // 此处可直接使用非空的myComponent }
如果你使用的是更早的Unity版本,可以自己扩展实现该方法:
public static class GameObjectExtension { public static bool TryGetComponent<T>(this GameObject gameObject, out T component) where T : Component { component = gameObject.GetComponent<T>(); return component != null; } }
扩展方法引入后即可和原生方法一样使用。
内容的提问来源于stack exchange,提问作者Orion31
相关产品推荐
相关产品推荐

