0
\$\begingroup\$

so I have a little project where I have 3 scenes - gameplay one with player and it's script, main menu with 2 buttons "Play" and "Shop" and shop scene with 2 buttons "Buy HP" and "Buy Speed". So I want to have an opportunity to change some stats on player from shop scene. I used PlayerPrefs for this and setted values in Start method of player's script.

[SerializeField] private int maxHP = 1; [SerializeField] private int hp = 0; [SerializeField] private float attackTimer = 2f; void Start() { if(maxHP == 1) { PlayerPrefs.SetInt("maxHP", maxHP); } else { if(PlayerPrefs.GetInt("maxHP") != null) { maxHP = PlayerPrefs.GetInt("maxHP"); } } PlayerPrefs.SetFloat("attackCD", attackTimer); rb = GetComponent<Rigidbody2D>(); currentAttackTimer = attackTimer; hp = maxHP; } 

so player's Start() method looks like this. Cause attackTimer is changing in the same way, I will put only maxHP as an example:

public void BuyHP() { if(PlayerPrefs.GetInt("maxHP") < 5) { int tmpHP = PlayerPrefs.GetInt("maxHP"); tmpHP++; PlayerPrefs.SetInt("maxHP", tmpHP); hpText.text = PlayerPrefs.GetInt("maxHP").ToString() + "/5"; } } 

this script is on button, it works to change value up to 5 times and rewrite it in "maxHP" key, but at the start of a gameplay scene I have maxHP = 1 anyway. Can somebody help me out and explain, mby I don't really know how PlayerPrefs works? Thx in advance

\$\endgroup\$
4
  • \$\begingroup\$ You want to know how playerprefs are working or how to transfer the data from one scene to another? One is like a registry key, storing values that are lasting even after you end the game, for the other one you could take a look at DontDestroyOnLoad \$\endgroup\$ Commented Feb 1, 2022 at 17:01
  • \$\begingroup\$ I want to transfer data, used PlayerPrefs cause my friend said that I can use it to solve my problem \$\endgroup\$ Commented Feb 1, 2022 at 17:03
  • \$\begingroup\$ You may be interested in past Q&A about sharing/transferring data between scenes in Untiy \$\endgroup\$ Commented Feb 1, 2022 at 17:04
  • \$\begingroup\$ @DMGregory ok, thx, will check this out \$\endgroup\$ Commented Feb 1, 2022 at 17:09

1 Answer 1

0
\$\begingroup\$

I used static class to transfer data, thx @DMGregory for the link - https://gamedev.stackexchange.com/search?q=%5Bunity%5D+between+scenes

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.