Coins won't save when i move to another scene

So im trying to make a coin system for my mobile game so that the player collides with the coin he gets +1 coin and i set up a script to do that but when i move to another scene and do PlayerPrefs.GetInt(“Coins”) i will always say 0… This is my GameController script and i would just use the functions in this script in my other scripts…If you need any more info ask…

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

public class GameController : MonoBehaviour
{
[SerializeField] private Text scoreText;
public int coins;

void Start() => coins = PlayerPrefs.GetInt("Coins");

void Update() => scoreText.text = "Coins: " + coins;

public void AddCoins() { 
coins += 5;
Debug.Log("Coins Added!");
}

public void RewardedCoins() {
coins += 10;
Debug.Log("Player was Rewarded!");
}

public void CoinsAmount()
{
PlayerPrefs.GetInt("Coins");
}

public void SaveCoins()
{
PlayerPrefs.SetInt("Coins", coins);
PlayerPrefs.Save();
Debug.Log("Coins Saved!");
}

}

You never call SaveCoins

I do call SaveCoins in another script after the coins are added

public GameController gameControl;

void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Food")
{
Destroy(collision.gameObject);
Collect.Play();
gameControl.AddCoins();
gameControl.SaveCoins();

Correction: you wrote some code that if executed at the right time with the right data might do something like you expect. But is that happening?

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

I already placed Debug.Log() and everything seems to be running…And “AddCoins()” works and adds coins as should but still even though everything is running (including SaveCoins() when i go in a different scene it resets to 0 and then even if i go back to the game scene where i had my coins it will be back to 0
7460578--915889--Debug.Log.png

Are you doing anything not posted above to extend the life of GameController beyond one scene? To me it looks like it would go away along with everything else when you change scenes.

Typically this is controlled by calling DontDestroyOnLoad() and then explicitly managing its lifecycle, which may be infinite, or else only for the duration of your game. You can look at GameManager tutorials for other examples.

This is the singleton pattern I like to use for these multi-scene-lived needs in Unity3D:

Simple Singleton (UnitySingleton):

Some super-simple Singleton examples to take and modify:

Simple Unity3D Singleton (no predefined data):

https://gist.github.com/kurtdekker/775bb97614047072f7004d6fb9ccce30

Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:

https://gist.github.com/kurtdekker/2f07be6f6a844cf82110fc42a774a625

These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

public void DestroyThyself()
{
   Destroy(gameObject);
   Instance = null;    // because destroy doesn't happen until end of frame
}

My game is set in 2D so what do i do then? Will that script work in Unity2D too?

It does not concern itself with how many Ds you have. It concerns itself with script lifecycle vis-a-vis scene changes.

You should familiarize yourself with Unity script lifecycles by working through some basic GameManager tutorials.

What am i supposed to rename the script to and where do i need to place SingletonSimple.Instance at? I am sorry but i am a begginer in C#

Definitely hurry over to Youtube and work through two or three different GameManager tutorials. It’s not something anyone here can tell you in the general sense, since it involves scene setup.

I don’t know if that is what i was trying to make. I have that script GameController which adds coins and saves and that and i just put it in an empty gameobject in each scene and i just link the script by doing “public GameController gameControl” and use its functions like that
But my problem is that when i run SaveCoins() and then run GetInt(“Coins”, coins) in another scene…it will not load the amount i had in the last scene (Also RewardedCoins doesn’t work for some reason and that is supposed to give me 10 coins when i watch a rewarded ad)

And I certainly don’t know either.

It’s hard to do something unless you know what it is.

Try some tutorials for what you want.

I have already watched a few but i didn’t work (Also this is probably important i am using unity version 2019.4)

Watching tutorials is NOT useful. Try this approach instead. It will save you a lot of time:

How to do tutorials properly:

Tutorials are a GREAT idea. Tutorials should be used this way:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly. Fortunately this is the easiest part to get right. Be a robot. Don’t make any mistakes. BE PERFECT IN EVERYTHING YOU DO HERE.

If you get any errors, learn how to read the error code and fix it. Google is your friend here. Do NOT continue until you fix the error. The error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.
Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

I do not think it is a spelling mistake otherwise i would be getting errors in my console and i kind of understand how my code works but it just doesn’t work when it should be?

Is it something that i might be missing outside of coding?
Is it maybe because of my unity version?
I am quite new to C# and Unity in general so it is probably something simple?

YES.

I have told you EXACTLY what it is multiple times above.

I will tell you one final time.

The behavior you are seeing is EXPECTED.

You are FAILING to set the object as DontDestroyOnLoad

I have shown you example code.

I have shown you example tutorials to search for.

You have claimed to have followed them and “they don’t work.”

I know they work.

I tried to guide you to the right way to do tutorials.

At this point I give up.

Good luck.

Alright, Thank you anyways!

I will again read through what you said and try to fix this.