I am new to game development and for exercise I made endless runner where everything is generated randomly from prefabs and both player and obstacles are being destroyed once they are off the screen. There are two scenes - Start and Game. At the Start scene you can click on Play button which will take you to the Game scene and you can mute the sound.
When I start the game and I click on the Play button it loads the Game scene perfectly and game runs and works just fine. When player dies the game over window is shown. From there two options are available - either go to the Start scene or play the game one more time.
If I choose to play one more time everything works perfectly. But if I choose to go to the Start scene and then click on Play button to play the game then once the Game scene is loaded the player and the obstacle game objects are not being generated and floor and background Quads are not being resized properly to fit the screen. And I get the following error -
MissingReferenceException: The object of type 'RecycleGameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
ObjectPool.NextObject (Vector3 pos) (at Assets/Scripts/ObjectPool.cs:28)
My question is - what can I do so that every time I come back to the scene everything is being loaded just like the first time?
I am currently loading scenes with this code:
SceneManager.LoadScene("Start");
And this is the ObjectPool class:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class ObjectPool : MonoBehaviour {
public RecycleGameObject prefab;
private List<RecycleGameObject> poolInstances = new List<RecycleGameObject>();
private RecycleGameObject CreateInstance(Vector3 pos)
{
var clone = GameObject.Instantiate(prefab);
clone.transform.position = pos;
clone.transform.parent = transform;
poolInstances.Add(clone);
return clone;
}
public RecycleGameObject NextObject(Vector3 pos)
{
RecycleGameObject instance = null;
foreach(var go in poolInstances)
{
if(go.gameObject.activeSelf != true)//here I get the error
{
instance = go;
instance.transform.position = pos;
}
}
if(instance == null)
{
instance = CreateInstance(pos);
}
instance.Restart();
return instance;
}
}