Hey guys,
so i made a endless runner on android(i know original right? hmmm…) And everything works fine at first. However when i die and press the restart button with the following code:
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
The game stops generating rooms? Any idea why? This is my generating rooms code:
void AddRoom(float farhtestRoomEndX) {
//pick a random room from the array and instantiate it.
int randomRoom = Random.Range(0, AllRooms.Length);
GameObject room = (GameObject)Instantiate(AllRooms[randomRoom]);
//Find the floor, and pos to instantiate(half of the screen) and add it to active rooms.
float roomWidth = room.transform.FindChild("Floor").localScale.x;
float roomCenter = farhtestRoomEndX + roomWidth * 0.5f;
room.transform.position = new Vector3(roomCenter, 0, 0);
ActiveRooms.Add(room);
}
void GenerateRoomIfRequired() {
//Create a new list with rooms to be deleted, and make a bool to check if rooms need to be added
List<GameObject> DeleteRooms = new List<GameObject>();
bool AddRooms = true;
//Save the playerPos, , calculate the point after when the room needs to be removed and calculate the starting pos for instantiating a new room
float playerX = transform.position.x;
float removeRoomX = playerX - screenWidthInPoints;
float addRoomX = playerX + screenWidthInPoints;
//store the point where the room ens, this is used to instantiate a new room aswell
float farthestRoomEndX = 0;
// use the floor to get the room width and calculate the roomStartX and roomEndX
foreach (var room in ActiveRooms) {
float roomWidth = room.transform.FindChild("Floor").localScale.x;
float roomStartX = room.transform.position.x - (roomWidth * 0.5f);
float roomEndX = roomStartX + roomWidth;
//If there is a room that starts after addRoomX, delete it. or ends to the left of removeRoomX, delete it
if (roomStartX > addRoomX)
AddRooms = false;
if (roomEndX < removeRoomX)
DeleteRooms.Add(room);
//the most right point of the level.
farthestRoomEndX = Mathf.Max(farthestRoomEndX, roomEndX -0.01f);
}
//remove rooms that are marked as removal, and if addRooms is still true, add a new room
foreach (var room in DeleteRooms) {
ActiveRooms.Remove(room);
Destroy(room);
}
if (AddRooms)
AddRoom(farthestRoomEndX);
}
The weird part is everything runs great the first time. (The code above is beeing called from a fixedupdate.)
EDIT: For those wondering about the fixedupdate. All it does it call the function above as following: GenerateRoomIfRequired();
EDIT 2: I found out that on restarting the scene it doesnt get passed this line:
float roomWidth = room.transform.FindChild(“Floor”).localScale.x;
This floor it’s trying to find is a child empty object with collider, inside the room prefab. Used to check if im hitting to floor