Collision Fires Gameover on Unity

Asked

Viewed 122 times

1

I’m developing a game in Unity that consists of building a building made by blocks, and my game has an initial block and the rest of the blocks are all the same and they are generated through code when the game does a certain thing, in my Game Over script I have the blocks with the tag "block" and what I need to do is when one of these blocks falls to the ground the game ends, but it’s not happening someone knows how to solve ? Script Code "Gameover" :

public class GameOver : MonoBehaviour
    {
    // Start is called before the first frame update
    public GameObject bloco;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "bloco")
        {
            SceneManager.LoadScene(4);
        }
    }
}
  • Your script is associated with which object?

1 answer

2


You can do two ways, check if the block collided with the floor or check if the floor collided with the block.

Create a script with the name DetetaColisao and associate with the block Prefab, then create a Plane and name chao

using UnityEngine;
using System.Collections;

public class DetetaColisao : MonoBehaviour
{
    // funcao para verificar todas colisoes do bloco
    void OnCollisionEnter2D (Collision2D col)
    {
        // o bloco colidiu com um gameobject que tem o nome "chao"
        if(col.gameObject.name == "chao")
        {
            // carrega a cena do gameover
            SceneManager.LoadScene(4);
        }
    }
}

Your script to work should be associated with "chao" in this case.

I don’t have Unity to test so the code may be subject to errors.

  • Thank you very much !!! Problem solved !!

  • Very well :) Consider marking the question as resolved. I don’t like to be rude but in the future avoid comments as a thank you and by the way take the opportunity to visit tour Stackoverflow if you have not done so. Welcome to the OS. the/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.