Hello! I am having trouble making text appear when my player collides with an obstacle. Here is the script I have attached to my “Game Over” text:
using UnityEngine;
using UnityEngine.UI;
public class ShowUI : MonoBehaviour
{
public Text gameOver;
void Start()
{
gameOver.enabled = false;
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
gameOver.enabled = true;
}
}
}
While the first part of the script seems to work, the text disappears when I click on play; when I hit an obstacle the text “Game Over” never appears. Here is a short video of the problem:
Not really sure what I am doing wrong, been looking at other forums and videos to try and fix the problem but nothing seems to be working. Any help would be very appreciated!
Hi!
So the thing is that you have OnCollisionEnter function in your ShowUI class, so, to make it clear, the OnCollisionEnter in your case will get called when other GameObject with Collider component will contact with the object on which you have the ShowUI class, the function isn’t checking all happened Collisions in the game.
I hope that’s clear, why it’s never get called - because the ShowUI isn’t the script that attached to the Asteroids or Player where you checking their Collisions (I assume).
So, as we can see in your video you have Collision detection between your player and your asteroids, so I suggest you to store the reference to the ShowUI in the Player class, so when you call your Death function you will enable the ShowUI gameOver variable.
I hope it helps.
Don’t use “.enabled” it’s easier to create a public GameObject and to use gameObject.SetActive(false/true).
public GameObject GameOverText
void Start()
{
GameOverText.SetActive(false);
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Player")
{
GameOverText.SetActive(true);
}
}