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.