Save bools from a scene to another in Unity

Viewed 55

I've trying to make an adventure game which saves different bools in order to get to the next scene. The problem is that one bool is in another scene with makes it null. Is there any advice?

public class Farmer : MonoBehaviour
{
    public bool NextLevel = false;
    public Cow1 cow1;
    public Cow2 cow2;
    public Cow3 cow3;
    public Dialogue dialogue;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (GetComponent<Cow1>().getIsDisplayed() && GetComponent<Cow2>().getIsDisplayed() && GetComponent<Cow3>().getIsDisplayed())
        {
            NextLevel = true;
        }
        if (NextLevel == true)
        {
            FindObjectOfType<DialogueManager>().startDialogue(dialogue);
        }
    }
}
2 Answers

Yes, there is quite an easy way to do this, simply give a game object the DontDestroyOnLoad property

{
    public bool NextLevel = false;
    public Cow1 cow1;
    public Cow2 cow2;
    public Cow3 cow3;
    public Dialogue dialogue;
    // Start is called before the first frame update
    void Start()
    {
         DontDestroyOnLoad(this.gameObject); 
    }

    // Update is called once per frame
    void Update()
    {
        if (GetComponent<Cow1>().getIsDisplayed() && GetComponent<Cow2>().getIsDisplayed() && GetComponent<Cow3>().getIsDisplayed())
        {
            NextLevel = true;
        }
        if (NextLevel == true)
        {
            FindObjectOfType<DialogueManager>().startDialogue(dialogue);
        }
    }
}

This will make your game object persistent through scene changes

You can make use of multi-scene editing so you have some values and variables carry on between your scenes. You can learn more about this here.

Related