- Home /
Other
Save values on different objets with same script?
Hello i am making a game like cookie clicker called booty slapper, and in the shop i have different items and when i buy one the price increases and thats working. But the problem is when im trying to save all items with player prefs because i have the same script attached to all the the objects and how can i save all items new price in the playerprefs script? I know how to use Playerprefs with one single object like this:
PlayerPrefs.SetFloat("currSlaps", gamemanagersc.currSlaps);
but not if i have many items with the same script. My item script:
public Text CostT;
public float Cost;
public int modifier;
public void Update()
{
CostT.text = "Cost: " + Cost.ToString("F0");
}
public void Buy()
{
GameObject gamemanager = GameObject.Find("GameManager");
gameManager gamemanagersc = gamemanager.GetComponent<gameManager>();
if(gamemanagersc.currSlaps >= Cost)
{
gamemanagersc.currSlaps -= Cost;
gamemanagersc.slapModifier += modifier;
Cost *= 1.25f;
}
}
It is the Cost value i want to save.
Answer by CodeMonkeyYT · Nov 11, 2019 at 04:05 PM
You can save the cost as a float value in the PlayerPrefs
PlayerPrefs.SetFloat("Cost", Cost);
Or use something like JSON to save your entire object with JsonUtility https://www.youtube.com/watch?v=6uMFEM-napE
@Code$$anonymous$$onkeyYT I get this error: NullReferenceException: Object reference not set to an instance of an object on: GameObject slapmodifier = GameObject.Find("Content"); Slap$$anonymous$$odifier slapmodsc = slapmodifier.GetComponent ();
slapmodsc.Cost = PlayerPrefs.GetFloat("newcostmod", slapmodsc.Cost);
and:
GameObject slapssecound = GameObject.Find("Content");
SlapsPerSecound slapsecsc = slapssecound.GetComponent<SlapsPerSecound>();
PlayerPrefs.SetFloat("newcostsec", slapsecsc.Cost);
PlayerPrefs.SetFloat("newcostmod", slapmodsc.Cost);
"Content" is inside viewport in a scroll wheel, and inside Content i have put all items with the script
here is a screenshot