KevinFruit
KevinFruit

Reputation: 1

Unity3D - Store data (e.g. int) between more scenes (2D Project)

i am new to coding and i would like to ask if someone can help me, i started off a project and want to save my money i have between more scenes, its a 2D Project.

I have something like:

public class Click : MonoBehaviour
{
    public UnityEngine.UI.Text cp;
    public UnityEngine.UI.Text goldDisplay;
    public float gold = 0.00f;
    public int goldperclick = 1;

    void Update()
    {
        goldDisplay.text = "  Fruits: " + gold;
        cp.text = "  CP: " + goldperclick;
    }

    public void Clicked()
    {
        gold += goldperclick;
    }
}

when i now switch the scene to another, and get back to that scene, all the money is lost, i would like to know if anybody could say what i can try to solve this problem.

Thanks.

Upvotes: 0

Views: 45

Answers (3)

OnionFan
OnionFan

Reputation: 511

Try a singletone pattern:

Read: https://msdn.microsoft.com/en-us/library/ff650316.aspx

Example:

using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }

   private int money; //Saved data

   public int Money //Access to field
   {
       get { return money; }
       set { money = value; }
   }
}

Upvotes: 0

Radomir Dinic
Radomir Dinic

Reputation: 11

You can simply call the GameObject's DontDestroyOnLoad() Method as described here. To avoid multiple instantiation, take care in which scene you do the initial instantiation of that gameobject.

Upvotes: 1

MiningSam
MiningSam

Reputation: 603

Here you go, a standard tutorial that will teach you about writing a game manager:

https://unity3d.com/learn/tutorials/projects/2d-roguelike-tutorial/writing-game-manager

Upvotes: 0

Related Questions