So i’m making an attempt to build a base for a future rpg game. I’m currently trying to make it so the player can transfer between scenes by using async and MoveGameObjectToScene. I can transfer scenes correctly but when i try changing scenes a second time it come up with an error message.
It also refuses to remove the previous scene as well. Can anyone help me please? Here is my code
SceneLoader
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneLoader : MonoBehaviour
{
public Vector2 newGateLocation;
private void Awake()
{
int sceneLoaderCount = FindObjectsOfType<SceneLoader>().Length;
if (sceneLoaderCount > 1)
{
Destroy(gameObject);
}
}
public IEnumerator ChangeLocation(string destination, string point)
{
AudioListener audioListener = FindObjectOfType<AudioListener>();
audioListener.enabled = false;
Scene currentScene = SceneManager.GetActiveScene();
Debug.Log("current scene is "+ currentScene.name);
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(destination, LoadSceneMode.Additive);
while (!asyncLoad.isDone)
{
yield return null;
}
SceneManager.MoveGameObjectToScene(gameObject, SceneManager.GetSceneByName(destination));
SceneManager.UnloadSceneAsync(currentScene);
newGateLocation = GameObject.Find(point).transform.position;
FindObjectOfType<Player>().setStartingPosition(newGateLocation);
Debug.Log(newGateLocation);
}
}
Gate
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gate : MonoBehaviour
{
[SerializeField] string targetScene;
string targetGate;
SceneLoader sceneLoader;
bool isActive = false;
// Start is called before the first frame update
void Start()
{
sceneLoader = FindObjectOfType<SceneLoader>();
targetGate = targetScene + " Gate";
Debug.Log(targetScene);
Debug.Log(targetGate);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isActive)
{
StartCoroutine(sceneLoader.ChangeLocation(targetScene, targetGate));
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
isActive = true;
Debug.Log("is active" + isActive);
}
private void OnTriggerExit2D(Collider2D collision)
{
isActive = false;
Debug.Log("is active" + isActive);
}
}