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.

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()

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.

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. :smiley: