Reputation: 1279
I am trying to get the scene to switch when a method in the script TrippleBall
returns 0. I know it returns 0 at the appropriate time because I have tested it. Here is my code to switch scenes:
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");
}
}
}
Here is an image to show where TrippleBalls
is
The script TrippleBall
is in the component TrippleBalls
Here is an image to show where the code above is located.
The code above is in a class called SceneTrigger
which has been put in LBackBoard
and RBackBoard
When I test the code, and the getBallCount
returns 0 (to satisfy the condition above) I get the following error:
Object reference not set to an instance of an object
This error line sends me to where i marked error
in the code above.
If anyone can help me figure this out, that would be awesome. Thank you!
Upvotes: 0
Views: 81
Reputation: 125455
You GameObject is named TrippleBall
in the Scene but you are looking for TrippleBalls
in the Scene. Simply change GameObject.Find("TrippleBalls")
to GameObject.Find("TrippleBall");
.
Also Don't use GameObject.Find in the OnTrigger function. It will slow down your game.Cach TripleBall in a local variable then you can re-use it.
TripleBall myTripleBall = null;
void Strt(){
//Cache TripleBall
myTripleBall = GameObject.Find("TrippleBalls").GetComponent<TripleBall>()
}
Now you can re-use it any time.
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");
}
}
}
Make sure to Add the GameOverScene scene in your Build Setting.
Advice:
Advice for you is that when Looking for another GameObject inside another GameObject, Use '/' like you would in a folder path. For example, TrippleBall is under Specialties GameObject. So use GameObject.Find("Specialties/TrippleBall");
instead of GameObject.Find("TrippleBall");
Upvotes: 3