Reset Score Count?

So I finally got collision to work and have my player die and respawn when he touches a certain object, but this doesn’t reset the score count. Here is my script I’m using that respawns the player:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class KillPlayer : MonoBehaviour
{
    public int Respawn;
    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
       
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            SceneManager.LoadScene(Respawn);
        }
    }
}

And here is my script that keeps the score count:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScoreScript : MonoBehaviour
{
    public static int scoreValue = 0;
    Text score;

    // Start is called before the first frame update
    void Start()
    {
        score = GetComponent<Text>();
    }

    // Update is called once per frame
    void Update()
    {
        score.text = "Score:" + scoreValue;
    }
}

So what function should I add and to which script that will reset the score to 0 upon player death? It seems I should be able to add it to the respawn function, but that doesn’t work. I hope this is clear. Much appreciated!

Since ur scoreValue is already public, you can access this variable in other scripts by accessing the GameObject that the ScoreScript is attached to.
Say the GameObject that ScoreScript is attached to is Scoreboard, in ur KillPlayer script you can add:

GameObject.Find("Scoreboard").GetComponent<ScoreScript>().scoreValue=0

Instead of using GameObject.Find(), u can also declare a public GameObject variable in KillPlayer, then drag the Scoreboard object to the corresponding value inside the object that KillPlayer is attached to in the editor

It’s actually a little more complicated than that because scoreValue is declared static.

Your given get-get-get code above won’t work in C# because you can’t get at static properties with class references.

As long as scoreValue continues to be static, this should work:

ScoreScript.scoreValue = 0;

Oh I didn’t see that’s static

1 Like

ScoreScript.scoreValue = 0; worked! Starting to understanding coding more and more, thanks for explaining the solutions. It helps a lot

1 Like