Sorry if this is a dumb question, but I’ve been stuck on this for days and can’t make heads or tales of anything I’ve found on Google so far even though I’ve likely read the answer already multiple times and just haven’t been able to understand it. If anyone can explain this simple concept to me, than please do so as if you were talking to a 5 year old because apparently my brain never got much further during development after that.
Basically I have a simple 2D Coin object in-game which has a 2D-Circle collider attached. When a collision happens, specifically with the player, then I would like it to add +1 ‘points’ to the PlayerPrefs current value for Points.
function OnCollision2D () {
PlayerPrefs.SetInt("Points", (PlayerPrefs.GetInt("Points")+1));
print (PlayerPrefs.GetInt("Points"));
}
The issue is that despite collision with the player or the world or well, anything really; nothing happens? I’m watching the value in the the registry and it’s sitting at a cozy 0. Can anyone offer some insight that isn’t a link to a tutorial video that I’ve already seen and didn’t get? Thanks.
tldr; I don’t understand the core concepts of a persistent currency system. Send help.
Although, why are you writing to the registry each time to update points? Why not have an int to store the points value? You can save the value to the registry when the game is closed or something.
Oh my god. I feel like such an idiot now. I’ve literally spent the last 3 days doing nothing but sitting at this and the solution was… so simple…
Thank you!
Here’s the working script I have now, in-case anyone needs this in the future. Just attach this script to the coin. Set the player character’s tag to “Player” and finally add a 2D-collider with a trigger to the coin object.
#pragma strict
function OnTriggerEnter2D(other: Collider2D) {
if (other.gameObject.tag =="Player")
PlayerPrefs.SetInt("Points", (PlayerPrefs.GetInt("Points")+1));
PlayerPrefs.Save ();
print (PlayerPrefs.GetInt("Points"));
}