Hi. I have a script that manages other scripts for my Player object.
The Player is DontDestroyOnLoad and i can’t figure out how to call a function on any scene change.
My code below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class ScriptSceneManager : MonoBehaviour
{
private PlayerMovement movement;
private PlayerBlock blockPlacing;
private Attacks attacking;
private GhostBlockManager ghostBlock;
private PlayerHotBar hotBar;
void Awake(){
movement = GetComponent<PlayerMovement>();
blockPlacing = GetComponent<PlayerBlock>();
attacking = GetComponent<Attacks>();
ghostBlock = GetComponent<GhostBlockManager>();
hotBar = GetComponent<PlayerHotBar>();
DontDestroyOnLoad(gameObject);
}
void Start(){
SceneManager.sceneLoaded += OnSceneLoaded;
}
void EnableFunctions(){
movement.enabled = true;
movement.reFindReferences();
blockPlacing.enabled = true;
blockPlacing.reFindReferences();
attacking.enabled = true;
hotBar.enabled = true;
ghostBlock.enabled = true;
}
public void DisableFunctions(){
blockPlacing.enabled = false;
attacking.enabled = false;
ghostBlock.enabled = false;
hotBar.enabled = false;
}
void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
print("Scene has loaded");
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
print("Scene on scene");
if (scene.name != "Testing" && scene.name != "Battle"){
DisableFunctions();
}
else if(scene.name == "Battle"){
print("is battle");
EnableFunctions();
Invoke("SetBattleSpawnPos", 0.2f);
SetBattleSpawnPos();
}
else if(scene.name == "Testing"){
EnableFunctions();
}
}
private void SetBattleSpawnPos(){
LevelGenerator gen = LevelGenerator.instance;
int xSpawnPos = gen.surfacemaxX/2;
Vector2 spawnPos = gen.getSurfacePos(xSpawnPos);
spawnPos.y += 1;
transform.position = spawnPos;
}
}
When changing scenes, OnSceneLoaded is never called. OnEnabled is only called once (when the object is created). How do i trigger OnSceneLoaded when a scene is loaded when my object has DontDestroyOnLoad? I want to be able to disabled and enable different functions based on which scene is loaded. Thanks.