- Home /
Space Shooter - NullReferenceException on Scene Reload
I'd like to get help on understanding the issue I'm having with Space Shooter tutorial. It was completed fully completed and on initial scene load works perfectly. But on restarting the scene the game is loosing number of objects with NullReferenceExpection raised on line
GameObject hazard = hazards[Random.Range(0, hazards.Length)];
Initial Background and Player objects still works, including sounds and Bolt, but following objects are not visible from the scene hierarchy: -Starfield - completely gone -Second Background (scrolling stopping to work) -Game Controller Hazards: Size becomes 0 and references to all Elements are gone.
On full game restart all the missing object reappearing (as per project) and gone again on the scene restart.
The _Complete_Game works perfectly. The scripts are fully compared and all visual issues are checked. Google hints on Awake() and etc. didn't help.
I think it's important to understand the issue before continue exploring Unity. I'd appreciate any idea.
Does the exact same object disappear each time ? What do you call restarting ? If I remember correctly the tutorial , is it when you press a key like "R" and then you go at the beginning of the level ? If so, can you provide the code of the function ?
I would check that there are no object created in Start() or Destroy on restart but it's hard to say without further information ...
Thank you for looking into this. The same objects consistently disappearing after pressing 'R' button. The code of the function:
void Update() { if (restart) { if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.R)) { Scene$$anonymous$$anager.LoadScene(Scene$$anonymous$$anager.GetActiveScene().buildIndex); } } }
Please see screenshots showing which objects are disappearing. Thank you!
[1]: /storage/temp/94641-afterscenerestart.jpg
I am not entirely sure, but try this:
GameObject hazard = hazards[Random.Range(0, hazards.Length - 1)];
That -1 is important because arrays begin at zero (not one). This method of counting causes the end index to be less one. I ran in to this exact problem recently. Of course then that would raise an array out of bounds exception when trying to get a value from the the last index...
are you sure hazards[] has anything within it? Has it got data or are there any null values inside it? Try a debugger to find out.
I didn't pay attention, but it's entirely possible that this line create an error that stop the loading of the scene in the middle, which explain why half of the object are missing.
Your answer
Follow this Question
Related Questions
Error after importing assets (Survival Shooter tutorial), Win32Exception 0 Answers
NullReferenceException: Object reference not set to an instance of an object 1 Answer
NullReferenceException. GetComponent dose not work properly 2 Answers
Why is the boundary not working? 1 Answer
[Closed]NullReferenceException on Object Instantiation onto game world 2 Answers