Home > database >  Unity cannot convert from 'float' to 'UnityEngine.Object' DontDestroyOnLoad
Unity cannot convert from 'float' to 'UnityEngine.Object' DontDestroyOnLoad

Time:01-04

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.

CodePudding user response:

public class Health : MonoBehaviour
{
    public Health Instance;
    //or public Health[] Instances for multiple instances of health
    [SerializeField] public float startingHealth;
    public float currentHealth;
 
    private void Awake() 
    {
     if(Instance == null){Instance == this}
     else{Destroy(this);}
     //keeps one script active, destroying any new copies
     //for multi instance, append this don't forget - remove old instances
     DontDestroyOnLoad(this);
     //refers to this instance, so non-static is saved
     //because monobehaviour, each instance calls this
    }

CodePudding user response:

You can only use DontDestroyOnLoad(); on game objects, and what you're trying to use that method on is a variable.

  •  Tags:  
  • Related