0

I'm trying to keep currentHealth variable the same when switching to another level by using DontDestroyOnLoad()

public class Health : MonoBehaviour
{
    [SerializeField] public float startingHealth;
    public float currentHealth;
 
    private void Awake() 
    {
        currentHealth = startingHealth;
        GameObject.DontDestroyOnLoad(this.currentHealth);
    }

but I'm facing with this error Argument 1: cannot convert from 'float' to 'UnityEngine.Object'

I'm new to Unity and I don't know how to use this method properly. Thank you in advance.

  • The error is right. Its not a game object. What are you actually trying to achieve – BugFinder Jan 02 '22 at 21:45
  • DontDestroyOnLoad only preserves GameObjects. Because "currentHealth" is tied to a Health class, you need to preserve this particular object. So you need to use "this" in the argument call "DontDestroyOnLoad(this)". However you will still need a reference to the Health script in another scene. Another solution (not a great one tho), is to make "currentHealth" static and then you can call it from anywhere (Health.currentHealth). – rootpanthera Jan 02 '22 at 21:45
  • Does this answer your question: [How to pass data (and references) between scenes in Unity](https://stackoverflow.com/questions/32306704/how-to-pass-data-and-references-between-scenes-in-unity) – derHugo Jan 03 '22 at 16:16

0 Answers0