- Home /
playerprefs and UI.
am i doing wrong? i want to the score increase on text UI when the object was destroyed, but when the object was destroyed, the score isn't increase or change.
int score = 0;
public Text ScoreText;
void Start()
{
ScoreText.text = "Score: " + PlayerPrefs.GetInt("myScore");
}
void Update()
{
for (var i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
if (Physics.Raycast(ray, out hit))
Destroy(hit.collider.gameObject);
score += 1;
PlayerPrefs.SetInt("myScore", score);
}
}
}
}
i have already assign the text UI on inspector of the object which i attached this script.
you need to update Text every time an object is destroyed.
Since 'if' statement has no {}. Only next line will be executed. That is 'Destroy'.
Because of this 'score+=1' will be updated everytime A finger touchesthe screen even if the touch doesn't destroys Object.
Put destroy, score and playerpref lines inside {} after 'if'. And update score text also inside {} after you update score.
Answer by Rhylvin2015 · Jul 04, 2015 at 05:04 AM
that's because you set your UI in void Start() which only happens the very first frame when you start the game. try putting in on your Update()
Answer by superbsumit · Jul 04, 2015 at 06:39 AM
In Update, you are only setting the 'PlayerPrefs', you have to update the 'ScoreText.text' value also, for displaying your score.
Also, increase the score only when the object gets destroyed as @Priyanshu suggested.
Answer by Vocus · Jul 04, 2015 at 09:53 AM
thank you guys. That very helpful
i just relize when i try @incorrect suggested. the score always increase when i touch the screen. then i try @Priyanshu suggest, i put the line destroy, score, scoreText, and playerprefs in {} after 'if' and it work.
int score = 0;
public Text ScoreText;
void Start()
{
}
void Update()
{
for (var i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
if (Physics.Raycast(ray, out hit))
{
Destroy(hit.collider.gameObject);
score += 1;
PlayerPrefs.SetInt("myScore", score);
ScoreText.text = "Score: " + score;
}
}
}
}
}
thank you so much guys. :D
No problem. But that was not Unity-specific question, it's general program$$anonymous$$g. Try to learn how to make algorithms and improve your skills. Good luck!
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Problems with saving/loading score with PlayerPrefs [C#] 1 Answer
Playerprefs not saving 1 Answer
How to use PlayerPrefs to activate game objects permanently? 1 Answer