Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 查找对象时,如何防止对象不在场景中_C#_Unity3d - Fatal编程技术网

C# 查找对象时,如何防止对象不在场景中

C# 查找对象时,如何防止对象不在场景中,c#,unity3d,C#,Unity3d,我现在有两个场景。第一个包含一个“通电”对象。所以剧本: myPowerUp = GameObject.FindObjectWithTag("Fuel").GetComponent<AddFuel>(); myPowerUp=GameObject.FindObjectWithTag(“Fuel”).GetComponent(); 查找对象 我努力想知道如何封装它,以便在第二个场景中,不会因为带标记(“燃料”)的对象不存在而引发错误 如果我使用这样的bool: if (!Powe

我现在有两个场景。第一个包含一个“通电”对象。所以剧本:

myPowerUp = GameObject.FindObjectWithTag("Fuel").GetComponent<AddFuel>();
myPowerUp=GameObject.FindObjectWithTag(“Fuel”).GetComponent();
查找对象

我努力想知道如何封装它,以便在第二个场景中,不会因为带标记(“燃料”)的对象不存在而引发错误

如果我使用这样的bool:

 if (!PowerUpExists){ 
    Return;
 } else {
 myPowerUp = GameObject.FindObjectWithTag("Fuel").GetComponent<AddFuel>() 
 }
如果(!PowerUpExists){
返回;
}否则{
myPowerUp=GameObject.FindObjectWithTag(“燃料”).GetComponent()
}
你喜欢那样的工作吗?我看不出这种逻辑会是怎样的,因为如果我不检查某个东西是否存在,如果你明白我的意思,我怎么能检查它是否存在


请帮帮我,我对这一点还不熟悉,正在学习,但绝对没有进步

只需检查游戏对象是否存在:

GameObject powerUpGo = GameObject.FindObjectWithTag("Fuel");
if( powerUpGo != null )
{
    myPowerUp = powerUpGo .GetComponent<AddFuel>() ;
}

否则,我只是建议您在inspector中直接序列化对象引用,以便在需要通电时进行空检查(并且您不再需要调用
Find


我可以考虑的最后一种可能性,但需要更多的“手动”工作,添加一个布尔值,您将根据当前所在的场景在检查器中进行检查

[SerializeField]
private bool powerUpExists; // Check / uncheck it in the inspector according to the scene you are working in

// ...

if (!powerUpExists)
{ 
    return;
}
else
{
    myPowerUp = GameObject.FindObjectWithTag("Fuel").GetComponent<AddFuel>() 
}
[序列化字段]
私有bool powerUpExists;//根据您正在工作的场景,在检查器中选中/取消选中它
// ...
如果(!powerUpExists)
{ 
返回;
}
其他的
{
myPowerUp=GameObject.FindObjectWithTag(“燃料”).GetComponent()
}

您也可以执行场景检入代码,但必须对其进行硬编码。类似于
if(SceneManager.GetActiveScene().buildIndex==X)powerUpExists=true的东西
Right,但我个人倾向于最小化代码中完成的工作。深入研究代码通常不如在编辑器中进行简单的检查/拖放。我不太喜欢所有的
FindXXX
方法,我更喜欢我提出的第二种解决方案。谢谢,我认为针对inspector的序列化bool是最干净的选择,尽管这会带来一定程度的风险,即在创建新场景时忘记设置它。我以后两个都试试,看看进展如何。谢谢你的回答!!
[SerializeField]
private AddFuel myPowerUp ; // Drag & drop the object in the inspector

// ...

if( myPowerUp != null )
{
    // Do something with myPowerUp
}
[SerializeField]
private bool powerUpExists; // Check / uncheck it in the inspector according to the scene you are working in

// ...

if (!powerUpExists)
{ 
    return;
}
else
{
    myPowerUp = GameObject.FindObjectWithTag("Fuel").GetComponent<AddFuel>() 
}