Hello everyone, I’m having trouble with the loading system in Unity3D, especially with how to handle it when you want to go from one scene to another via a gameobject. What I mean by that is :
- I have a GameObject, an Elevator;
- The Elevator can go up or down, depending on what direction the elevator comes from. It can only go to another floor, which is always the same. So two elevators in two distinct scenes are corelated by ID;
- The Elevator is in a State Machine, to better handle the multiple states it can assume;
- The Elevator, when taken, triggers an animation (the doors closes, the elevator goes up or down), and when the animation ends, the script triggers a
ElevatorLoadScene(int ElevatorID, string SceneName)
method;
I almost never worked with the SceneManager in Unity, so I don’t know why my code is not good, but here it is :
/// <summary>
/// Loads a scene when you use an elevator.
/// </summary>
/// <param name="SceneName">The scene's name.</param>
/// <param name="ElevatorID">The elevator's ID.</param>
public void ElevatorLoadScene(string SceneName, int ElevatorID)
{
Scene sceneType = SceneManager.GetSceneByName(SceneName);
SceneManager.LoadScene(SceneName);
// Check every elevator in the list.
ElevatorList.Clear();
if (sceneType.IsValid()) TMPobjects = sceneType.GetRootGameObjects();
// For each GameObject with layer Elevator, add it to the list.
foreach (GameObject gameObject in TMPobjects)
{
if (gameObject.layer == 12)
{
ElevatorList.Add(gameObject);
}
}
// For each Elevator in ElevatorList, check if the ID is the right one.
foreach (GameObject ElevatorGM in ElevatorList)
{
ElevatorObject ElevatorGMC = ElevatorGM.GetComponent<ElevatorObject>();
if (ElevatorGMC.ElevatorID == ElevatorID)
{
// Assigns the elevator's position.
if (ElevatorGMC.IsGoingUp) ElevatorGMC.ElevatorRenderer.transform.position = ElevatorGMC.ElevatorUpPosition;
else ElevatorGMC.ElevatorRenderer.transform.position = ElevatorGMC.ElevatorDownPosition;
// Assigns the player's position to the elevator's position.
Vector3 elevatorPos = ElevatorGMC.ElevatorRenderer.transform.position;
Quaternion elevatorRot = ElevatorGMC.ElevatorRenderer.transform.rotation;
Player.PlayerInstance.transform.position = elevatorPos;
Player.PlayerInstance.transform.rotation = elevatorRot;
// Launches the elevator's next state.
ElevatorGMC.ElevatorRenderer.SetActive(true);
ElevatorGMC.SwitchState(ElevatorObject.comingWithThePlayerState);
break;
}
}
}
The code runs fine until it reaches the if (sceneType.IsValid()) TMPobjects = sceneType.GetRootGameObjects();
line, where it seems the scene is not valid. I simply want the player to be on the next scene ElevatorRenderer’s position, when I launch this method. I tried to find solutions on the internet, but now I just can’t seem to understand what I’m doing wrong. If someone is kind enough to take some time and explain what’s the problem, or simply redirect me, I would gladly appreciate. Thank you !