Hi, I have been trying to use these scripts for some collectible objects so they don’t respawn when I reload the game, however I cannot get it to work.
Here are the scripts I’m using:
using System.Linq;
using UnityEngine;
public class GamePersist : MonoBehaviour
{
void OnDisable() => Save();
void OnEnable() => Load();
void Load()
{
foreach (var persist in FindObjectsOfType<MonoBehaviour>(true).OfType<ISaveState>())
{
persist.Load();
}
}
void Save()
{
foreach(var persist in FindObjectsOfType<MonoBehaviour>(true).OfType<ISaveState>())
{
persist.Save();
}
}
}
internal interface ISaveState
{
void Save();
void Load();
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cratebox : MonoBehaviour, ISaveState
{
public GameObject currencyprefab;
public GameObject Destruction;
public Transform cratepos;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Bullet"))
{
gameObject.SetActive(false);
Instantiate(currencyprefab, cratepos.position, cratepos.rotation);
Instantiate(currencyprefab, cratepos.position, cratepos.rotation);
Instantiate(currencyprefab, cratepos.position, cratepos.rotation);
Instantiate(Destruction, cratepos.position, cratepos.rotation);
}
if (collision.gameObject.CompareTag("Stomp"))
{
gameObject.SetActive(false);
Instantiate(currencyprefab, cratepos.position, cratepos.rotation);
Instantiate(currencyprefab, cratepos.position, cratepos.rotation);
Instantiate(currencyprefab, cratepos.position, cratepos.rotation);
Instantiate(Destruction, cratepos.position, cratepos.rotation);
}
}
public string PickedUpKey => $"Crate - { gameObject.name } -PickedUp";
public void Save()
{
PlayerPrefs.SetInt(PickedUpKey, gameObject.activeSelf ? 0 : 1);
}
public void Load()
{
int isActive = PlayerPrefs.GetInt(PickedUpKey);
if(isActive ==1)
{
gameObject.SetActive(isActive == 1);
}
}
}
The cratebox script is attached to the collectible while the GamePersist is attached to another object. Supposedly when the GamePersist is disabled the cratebox’s state should be saved and when the GamePersist is reenabled after resetting the game, the cratebox should be disabled if I have collected the item last game, but it is not happening.