- Home /
How do i preserve my Prefab when changing scene?
i use a singleton to save my prefabs and the player position in the scene 1. it looks like this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorldData : MonoBehaviour
{
private static WorldData _instance;
public static WorldData Instance { get { return _instance; } }
public GameObject playerPrefab;
public GameObject enemyPrefab;
public float[] pos = new float[2];
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(this.gameObject);
}
else
{
_instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
and here is the code that should trigger the preserving data and changing scene.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyDetection : MonoBehaviour
{
public PlayerState state;
// Start is called before the first frame update
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Enemy"))
{
state.SetState(_PlayerState.BATTLE);
WorldData.Instance.playerPrefab = gameObject;
WorldData.Instance.enemyPrefab = collision.gameObject;
WorldData.Instance.pos[0] = transform.position.x;
WorldData.Instance.pos[1] = transform.position.y;
ScenesManager.Instance.ChangeScene("battlescene");
}
}
}
the data is stored when i dont change the scene. but it became missing when i change then scene to scene 2. even though i already used DontDestroyOnLoad(). i am new to unity and i really appreciate your help.
Answer by Monsoonexe · May 21, 2021 at 06:19 PM
DontDestroyOnLoad
makes it so the WorldData doesn't get destroyed, but everything else in the scene will be destroyed, including all EnemyDetection behaviours. So references (like gameObject
on lines 17 and 18) will be missing since their objects are destroyed.
It seems like you'll need to either DontDestroyOnLoad
each EnemyDetection behaviour or save the runtime data of each enemy (position, state, etc), and then respawn and re-update to that state in the new scene.
Your answer
Follow this Question
Related Questions
How can i transfer an object from scene1 and instantiate it in scene2? 2 Answers
public text prefab goes null after scene switching,Text prefab is null after reloading the scene 0 Answers
getting prefabs form project to another 3 Answers
Help how to reference prefab for instantiating between loads. 0 Answers