I'm trying to make a 2D platformer game and I am having a problem with trying to pass score to next scene and also if I use onDestroy method I can't reset the score when player dies. How would you go about doing it? This is my script for collecting items:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Collecting_Items : MonoBehaviour {
[SerializeField] private Text coinsberryText;
[SerializeField] private int coinsberry;
public Text pointsText;
[SerializeField] private AudioSource collectSoundEffect;
private void OnEnable() {
if (PlayerPrefs.HasKey("Strawberry"))
{
coinsberry = PlayerPrefs.GetInt("Strawberry");
}
}
private void OnTriggerEnter2D(Collider2D collision) {
if (collision.CompareTag("Strawberry"))
{
Destroy(collision.gameObject);
AddScore();
collectSoundEffect.Play();
}
}
void AddScore() {
coinsberry++;
coinsberryText.text = " :" + coinsberry;
Setup(coinsberry);
}
public void OnDestroy() {
savePrefs();
}
void savePrefs() {
PlayerPrefs.SetInt("Strawberry",coinsberry);
PlayerPrefs.Save();
}
public void Setup(int score)
{
gameObject.SetActive(true);
pointsText.text = score.ToString() + " :Strawberry";
}
}
This is my code for restart level
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManagerScript : MonoBehaviour {
public GameObject gameOverUI;
public GameObject scoreUI;
public static GameManagerScript instance;
public void gameOver() {
gameOverUI.SetActive(true);
scoreUI.SetActive(false);
PlayerPrefs.DeleteAll();
}
public void restart() {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public void mainMenu() {
SceneManager.LoadScene("Start Scene 1");
}
public void quit() {
Application.Quit();
Debug.Log("Quit");
}
}
So I tried on DontDestoryOnLoad but that for some reason ended the next scene out of nowhere so then I went and tried playerprefs it works but not as intended if anyone is willing to help it will be greatly appricated thanks.