Can PlayerPrefs be accessed in different scripts - c#
What I'm trying to do is use PlayerPrefs so I can can keep the score the same when the level is reloaded, but I need to use it in a different script so I can add to the score as well. Is this possible?
Script 1:
void Awake()
{
PlayerPrefs.SetInt("lives", 3);
PlayerPrefs.SetInt("score", 0);
}
public void ScoreText()
{
scoreText.text = "Score: " + PlayerPrefs.GetInt("score");
}
public void Wintext()
{
if (PlayerPrefs.GetInt("score") == 100)
{
winText.text = "You Win!";
}
}
script 2:
public void OnTriggerEnter2D(Collider2D other)
{
if(other.CompareTag("Enemy"))
{
Destroy(other.gameObject);
if(!other.isActiveAndEnabled)
{
PlayerControllerScript.+= 10; //Here is where I need to use the PlayerPrefs
PlayerControllerScript.ScoreText();
}
}
Destroy (gameObject);
}
Any reason you are not using a static class to hold the score (static classes won't reset when the level is reloaded)?
Answer by pako · Sep 12, 2015 at 06:47 PM
Yes you can access PlayerPrefs from different scripts, but PlayerPrefs is really meant for storing values between sessions. That's its main use.
If you just want to store score between levels it seems best to use a static class as @Rostam24 pointed out.
However, it's a bit unclear what you really want to do:
PlayerControllerScript.+= 10; //Here is where I need to use the PlayerPrefs
You must have missed something there. Doing some guesswork, it seems that Script 1 is your PlayerControllerScript and you want to access it from Script 2, because there's nothing in your code showing two different scripts accessing PlayerPrefs. You only show Script 1 accessing PlayerPrefs.
Yeah I didn't know what a static class was but I watched the tutorial and I'm implementing it into the code.
Answer by Shoon · Sep 12, 2015 at 07:10 PM
Of course you can do that, PlayerPrefs can be accessed from anywhere.
You would just do this to increse by 10 your PlayerPref:
PlayerPrefs.SetInt("score", PlayerPrefs.GetInt("score") + 10);
Your answer
Follow this Question
Related Questions
Playerpref Saving Lag 1 Answer
save a int with playerprefs for one instance of a gameobject 0 Answers
Highscore and PlayerPrefs unity C# 1 Answer