Prefabs data just show if it is triggered

Hi Unity Community!
I hope this question is not to stupid…:slight_smile:

My problem:
I setup :


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MoneyAdd : MonoBehaviour
{
private Text money;
private int moneyAmount;

void Start()
{
moneyAmount = PlayerPrefs.GetInt(“moneyKey”);
money = GetComponent();
}

void Update()
{
}
public void AddMoney()
{
moneyAmount += 10;
money.text = moneyAmount.ToString();
PlayerPrefs.SetInt(“moneyKey”, moneyAmount);
PlayerPrefs.Save();
}
}


My problem: The AddMoney () function works and saves, but not quite correctly the way I want it to. If I switch to GameMode and trigger AddMoney (), the int counts up 10, 20, 30, 40, 50 … When I exit GameMode, it sets the int back to 1. If I then switch back to GameMode, the int is not at 50 but at 1 again, if I run AddMoney () again, it doesn’t count up from 10, but starts at 50 and goes to 60, 70, 80. … That tells me that saving works, but I would like the int 1 to be at 50 immediately when the GameMode is started and I don’t have to trigger AddMoney () again first to get the correct int. I hope it’s more or less understandable … Is there some way I can do something in the void Start () to make this work?

Picture 1: Before enter GameMode first
Picture 2: In GameMode trigger AddMoney() 5 times
Picture 3: After i go out of GameMode and immedieatly go another time in GameMode, int is set back to 1
Picture 4: Than i trigger AddMoney() again, the count start at 60
(Green is GameMode)

6945176--816674--1.png
6945176--816677--2.png
6945176--816680--3.png
6945176--816683--4.png

Ohhhh, i love Unity <3

Here is the correct answer:


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class MoneyAdd : MonoBehaviour
{

private Text money;
private int moneyAmount;

// Start is called before the first frame update
void Start()
{
moneyAmount = PlayerPrefs.GetInt(“moneyKey”);
money = GetComponent();
money.text = moneyAmount.ToString();
PlayerPrefs.SetInt(“moneyKey”, moneyAmount);
}

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

}

public void AddMoney()
{
moneyAmount += 10;
money.text = moneyAmount.ToString();
PlayerPrefs.SetInt(“moneyKey”, moneyAmount);
PlayerPrefs.Save();
}

}


I know i shouldnt, but i’m a little bit proud to find the right answer by myself :slight_smile:

Admins: Should i delete the thread?