- Home /
Save Player Health in between scene loading
I'm making a game in which I want the player's health to be saved between scenes. I am trying to do this by having the player health be saved to a game manager and then loaded once the scene changes. This is what I've come up with so far
playerHealth:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
public float Health;
public float maxHealth;
public Animator anim;
public SimpleHealthBar healthBar;
// Start is called before the first frame update
void Start()
{
//Load Health
Health = FindObjectOfType<GameMaster>().playerHealth;
}
//Take Damage
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag == "Enemy")
{
Health -= 1f;
healthBar.UpdateBar(Health, maxHealth);
Debug.Log("You now have " + Health + " health left.");
}
}
//Change Healthbar
void Update()
{
healthBar.UpdateBar(Health, maxHealth);
if (Input.GetKeyDown(KeyCode.F))
{
Health = 0f;
}
//Kill Player
if(Health <= 0)
{
Destroy(gameObject);
Scene scene =
SceneManager.GetActiveScene();
SceneManager.LoadSceneAsync(scene.name);
}
//Health Bar Color Change
if(Health <= 4f)
{
healthBar.UpdateColor(Color.red);
}
if(Health > 4f)
{
healthBar.UpdateColor(Color.cyan);
}
}
public void SavePlayer()
{
FindObjectOfType<GameMaster>().playerHealth = Health;
}
}
` Gamemaster:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameMaster : MonoBehaviour
{
private static GameMaster Instance;
public Vector2 lastCheckpointPos;
public float Currency;
public float playerHealth;
void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(Instance);
}
else
{
Destroy(gameObject);
}
}
}
I can't figure out a way to call the SavePlayer variable when the scene is chaning. Any ideas?
Answer by robnw · Jun 13, 2019 at 02:29 AM
EDIT: saw the mistake, gonna edit this for future viewers with the comment/remove the obvious error:
Woops. Didn't see that. My original idea was to sub to an event as another commenter suggested. But on second thought you can have different scripts call a RequestChangeLevel()
function in GameManager (since you have the singleton going on), which would tell SceneManager and any relevant GUI to update. Keeps things cleaner instead of random scripts calling SceneManager and managing levels, and the GameManager having to subscribe to events that most scritps will have.
@robnw That part of the code is for reloading the scene once the player dies and not when switching between 2 scenes.
Then call SavePlayer() directly when you switch scenes elsewhere the same way you are calling Game$$anonymous$$aster by FindObjectOfType, but finding the play.
Or create a delegate and add SavePlayer() as a listener, then call the delegate event before changing scenes. https://learn.unity.com/tutorial/events-uh
Wow, I have no clue on why I didn't think about that! Thanks Bradylrv.