Bailey Mc Jarrow
Bailey Mc Jarrow

Reputation: 43

Score reset on Reload

I know that there are many similar questions but none of them seem to be quite the same as mine. I have a score that increments by one every time an object is destroyed and that works fine but I want to reset it to 0 when I reload the scene... For some reason it won't reset, everything else works fine.

variables:

public Text Score;
public static int counter;
public Transform obstacle;
public GameObject Obstacle;

code to increment when the object is destroyed:

 void Update()
{
    if (Obstacle.transform.position.z <= -5)
    {
        DestroyObstacle(Obstacle);
    }
   
    Score.text = (counter / 3).ToString();

}
void DestroyObstacle(GameObject Obstacle)
{
    Destroy(Obstacle);
    counter++;
}

}

The following code stops everything and brings up a button. When that button is clicked, it reloads the level as you can see, yet the score does not reset:

 public void OnCollisionEnter(Collision collision)
{
    if (collision.collider.tag == "Obstacle")
    {
        movement.enabled = false;
        Spawner.enabled = false;
        
        PlayButton.enabled = true;
        PlayText.enabled = true;

        PlayButton.onClick.AddListener(TaskOnClick);
        
    }
}
void TaskOnClick()
{

    Score.text = 0.ToString();
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

}

I know that it is probably something simple but I would really appreciate the help. Also! For some reason, if my counter is not a static int, the score will not increase? That's why it is static.

Upvotes: 1

Views: 136

Answers (2)

Entapsia
Entapsia

Reputation: 51

Because counter is static, it won't reset. It won't increment if it is not because the object with the incremented value is destroyed.

You need another script that will have the counter variable and will increment it when an object is destroyed.

Replace the line

counter++;

by

Camera.main.GetComponent<ScoreCounter>().Increase();

And do another class (something like that) and add the script on your camera :

public class ScoreCounter : MonoBehaviour
{
    public int counter;
    public Text Score;

    public void Increase()
    {
        counter++;
        Score.text = (counter / 3).ToString();
    }

}

Upvotes: 2

seandon47
seandon47

Reputation: 286

It's because counter is static, and as such it belongs to the class and not the object. It won't reset unless there's a hard restart. Adding counter = 0 as the first line in your TaskOnClick would do it, or changing counter to not be static and be a member of the object.

Upvotes: 1

Related Questions