The first Script which calculates score and stores in Playerprefs.
using UnityEngine;
using System.Collections;
public class Scores : MonoBehaviour {
private int score;
// Use this for initialization
void Awake () {
PlayerPrefs.SetInt("score",0);
}
public void AddScore()
{
score = score + 1;
PlayerPrefs.SetInt("score", score);
Debug.Log(score);
}
}
Second Script which calls this first script for updating score.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Scores))]
public class TheCollision : MonoBehaviour {
public Pool pool;
public Poolb poolb;
private Scores scores;
void Start()
{
scores = GetComponent<Scores>();
}
void OnTriggerEnter(Collider other)
{
if(other.tag == "moving")
{
poolb.deActivate(gameObject);
pool.deActivate(other.gameObject);
Debug.Log("Hitting the moving object");
scores.AddScore();
}
if(other.tag == "still")
{
poolb.deActivate(gameObject);
Debug.Log("Hitting the Still object");
Application.Quit();
}
}
}
And there is this third script which displays the score on canvas UI text
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DisplayScore : MonoBehaviour {
Text txt;
// Use this for initialization
void Start () {
txt = gameObject.GetComponent<Text>();
}
// Update is called once per frame
void Update () {
txt.text="Score : " + PlayerPrefs.GetInt("score");
}
}
BUT WHILE PLAYING MY SCORE RESETS BACK TO 0 SOMETIMES. SOMETIMES DROPS TO ANY RANDOM NUMBER NUMBER 4 2.
I dont know what is the problem here.
And please write a proper mechanism to update a score and access it. I guess my method is too naive and error prone.