unity-game-enginebuttonrestartcollider

Collider2d not working when game restarted after player die


I've checked the In-Game Restart button, it works like a charm, player still can be hurt by colliding with the obstacle, but when the player die and press Restart button, the player won't collide with any obstacle,

So i think it's because my "void Die", but i only disable a few also it still works when i restart the game, only the player won't collide with any obstacle, just that... Help Me!

public void Die() {
    //Disable Score
    ScoreCounter.SetActive(false);

    //Animation
    AN.Play("Death");

    //Stop Coroutine
    StopCoroutine("Invulnerability");

    //Load Restart Menu
    PanelRestart.SetActive(true);

    //Disable Object Function
    GetComponent<CapsuleCollider2D>().enabled = false;
    this.enabled = false;
}

and this is my pause button script, i used this both in-game pause button and then restart, and when the player die and then restart

public void RestartButton() {
    SceneManager.LoadScene(1);
}

Solution

  • When I restart the game, only the player won't collide with any obstacle

    It's highly likely that your collisions aren't the problem, but your StopCoroutine() call is. As it currently won't stop the "Invulnerability" of the player and therefore he won't die once he collides.

    To fix that you need to adjust your StopCoroutine() call like this, you could either:

    1. Keep the IEnumerator Method as a private member.
    2. Keep the started Coroutine as a private member.

    IEnumerator Example:

    // Keep the executing script as a private variable.
    // This is needed to stop it with StopCoroutine.
    private IEnumerator coroutine;
    
    void Start() {
        coroutine = ExampleIEnumerator();
        // Start the given Coroutine.
        StartCoroutine(coroutine);
        // Stop the given Coroutine.
        StopCoroutine(coroutine);
    }
    
    private IEnumerator ExampleIEnumerator() {
        yield return new WaitForSeconds(1f);
    }
    

    Coroutine Example:

    // Keep the executed coroutine as a private variable.
    // This is needed to stop it with StopCoroutine.
    private Coroutine coroutine;
    
    void Start() {
        // Start the given Coroutine.
        coroutine = StartCoroutine(ExampleIEnumerator());
        // Stop the given Coroutine.
        StopCoroutine(coroutine);
    }
    
    private IEnumerator ExampleIEnumerator() {
        yield return new WaitForSeconds(1f);
    }
    

    Additionally you also need to re-enable your CapsuleCollider2D after disabling it when you die.

    GetComponent<CapsuleCollider2D>().enabled = true;
    

    StopCoroutine Unity Documentation