2016-05-17 91 views
0

我试图在脚本TrippleBall中的方法返回0时切换场景。我知道它在适当的时候返回0,因为我已经测试了它。这里是我的代码来切换场景:触发器不在Unity中激活

void OnTriggerEnter(Collider col) 
{ 
    if (col.gameObject.tag == "ball") 
    { 
     col.gameObject.GetComponent<Ball>().setIsOffScreen(true); 
     /*error*/ if (GameObject.Find("TrippleBalls").GetComponent<TripleBall>().getBallCount() == 0) { 

      Debug.Log("Loading next screen..."); 
      SceneManager.LoadScene("GameOverScene"); 
     } 

    } 

} 

这里是一个图像显示,其中TrippleBalls

enter image description here

脚本TrippleBall是在组件TrippleBalls

这里是一个图像显示上面的代码位于何处。

enter image description here

上面的代码是在一个称为类已经投入LBackBoardRBackBoard

当我测试的代码,并且getBallCount返回0(以满足条件以上)我得到以下错误:

Object reference not set to an instance of an object

此错误行送我到我打上error在上面的代码中。

如果任何人都可以帮我弄清楚,那就太棒了。谢谢!

回答

3

您的GameObject在场景中被命名为TrippleBall,但您正在场景中寻找TrippleBalls。只需将GameObject.Find("TrippleBalls")更改为GameObject.Find("TrippleBall");即可。

另请勿在OnTrigger函数中使用GameObject.Find。它会减慢你的游戏速度。在一个局部变量中使用TripleBall,然后你可以重新使用它。

TripleBall myTripleBall = null; 

void Strt(){ 
//Cache TripleBall 
myTripleBall = GameObject.Find("TrippleBalls").GetComponent<TripleBall>() 
} 

现在您可以随时重新使用它。

void OnTriggerEnter(Collider col) 
{ 
    if (col.gameObject.tag == "ball") 
    { 
     Debug.Log("COUNT IS: "+myTripleBall.getBallCount()); 
     col.gameObject.GetComponent<Ball>().setIsOffScreen(true); 
     if (myTripleBall.getBallCount() == 0) { 

      Debug.Log("Loading next screen..."); 
      SceneManager.LoadScene("GameOverScene"); 
     } 
    } 
} 

确保添加GameOverScene场景在构建设置。 enter image description here

建议:你 的建议是,对里面的另一个游戏物体,使用“/”另一个游戏物体看时,就像您在一个文件夹路径。例如,TrippleBall在Specialties GameObject下。因此,使用GameObject.Find("Specialties/TrippleBall");而不是GameObject.Find("TrippleBall");

+0

错误消失,但它仍然没有打印或更改场景 – Luke

+0

@Luke请确保在您的生成设置中添加GameOverScene场景。 – Programmer

+0

我做了所有这一切,但仍然无法正常工作。我甚至测试了加载下一个场景,并且工作。 – Luke