Search code examples
c#unity-game-enginescenesaving-data

Unity C# Passing Data Between Scenes


I am currently working on a in-app purchase store for my game which is found on a different scene. The trouble I am having is when I click a button for example for a new skin like white skin, in that scene it will save the data that the bool of "didwhiteskin" becomes true although when I load the gamescene it wont save this data therefore not run whats inside the if statement.Thank you for yall help and I will answer any questions if needed.

Additional Info: The function ChoseWhiteSkin() is called when a button clicked on StoreView.

Heres my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class StoreScript : MonoBehaviour {

    bool didwhiteskin = false;

    public static StoreScript Instance {
        get;
        set;
    }

    void Awake () {
        DontDestroyOnLoad (transform.gameObject);
        Instance = this;
    }

    // Use this for initialization
    void Start () {
        Scene currentScene = SceneManager.GetActiveScene ();
        string sceneName = currentScene.name;

        if (sceneName == "GameScene") {
            if (didwhiteskin) {
                Debug.Log ("this ran");
                //This where I will put function to change skin but the issue is the if statement never being ran
            }
        }
        else if (sceneName == "StoreView") {

        }
    }

    // Update is called once per frame
    void Update () {

    }

    public void ChoseWhiteSkin() {
        PlayerPrefs.Save();
        didwhiteskin = true;
    }
}

Solution

  • You can define a global variable for all scenes like this:

    public static int didwhiteskin = 0;
    

    So you can declare and initialise this variable in your first scene in the game, and then just refer it in any other scene you may create.