C# Unity-获取组件并在一行中检查Null?

C# Unity-获取组件并在一行中检查Null?,c#,unity3d,C#,Unity3d,有没有办法简化下面的代码块 MyComponent myComponent = gameObject.GetComponent<MyComponent>(); if (myComponent != null) { // do something } MyComponent MyComponent=gameObject.GetComponent(); 如果(myComponent!=null) { //做点什么 } 差不多 if (var myComponent = gam

有没有办法简化下面的代码块

MyComponent myComponent = gameObject.GetComponent<MyComponent>();
if (myComponent != null)
{
    // do something
}
MyComponent MyComponent=gameObject.GetComponent();
如果(myComponent!=null)
{
//做点什么
}
差不多

if (var myComponent = gameObject.GetComponent<MyComponent>() != null) {
    // do something
}
ComponentOne componentOne = gameObject.GetComponent<ComponentOne>();
if (componentOne != null)
{
    // do something
    return;
}

ComponentTwo componentTwo = gameObject.GetComponent<ComponentTwo>();
if (componentTwo != null)
{
    // do something
    return;
}

ComponentThree componentThree = gameObject.GetComponent<ComponentThree >();
if (componentThree != null)
{
    // do something
    return;
}
if(var myComponent=gameObject.GetComponent()!=null){
//做点什么
}
我这样做的动机是因为我用光线投射鼠标按键,我想让用户点击的对象类型影响所发生的事情。例如,我会做一些像

if (var myComponent = gameObject.GetComponent<MyComponent>() != null) {
    // do something
}
ComponentOne componentOne = gameObject.GetComponent<ComponentOne>();
if (componentOne != null)
{
    // do something
    return;
}

ComponentTwo componentTwo = gameObject.GetComponent<ComponentTwo>();
if (componentTwo != null)
{
    // do something
    return;
}

ComponentThree componentThree = gameObject.GetComponent<ComponentThree >();
if (componentThree != null)
{
    // do something
    return;
}
ComponentOne-ComponentOne=gameObject.GetComponent();
如果(componentOne!=null)
{
//做点什么
返回;
}
ComponentTwo-ComponentTwo=gameObject.GetComponent();
if(componentTwo!=null)
{
//做点什么
返回;
}
ComponentThree ComponentThree=gameObject.GetComponent();
如果(组件三!=null)
{
//做点什么
返回;
}
但是,这是混乱的,而且不必要的冗长。

那么:

MyComponent myComponent = gameObject.GetComponent<MyComponent>();
if (myComponent == null) return

// do something
MyComponent MyComponent=gameObject.GetComponent();
if(myComponent==null)返回
//做点什么
您正在寻找的


通过这种方式,您可以避免额外的花括号,但仍然没有一行在我的特定情况下,我正在光线投射鼠标按键,我希望功能根据单击的对象类型进行更改。我将更新这个问题,使之更清楚。这些不同的组件是否来自一个公共基类(可能不是
组件
^^)?