I’m making a simple Arkanoid clone. When the ball goes below the paddle, I want “Game Over” to display in the middle of the screen. So when the game starts, I set the text to “” so there’s nothing displaying during gameplay. Then, when the ball goes through the lower boundary trigger, I set the text to “Game Over”. Only problem is, none of that works. I know there must be something really simply behind it. I thought I had a good handle on how to do UI Text at least, but apparently not :'D. Here’s my code, and I’ve commented every section where I do something with text. I’ve included a couple screenshots from the editor at the end.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Ball : MonoBehaviour
{
public float speed = 100.0f;
private new Rigidbody2D rigidbody;
private SoundControllerScript soundController;
public Text gameOverText; //text variable
void Start()
{
gameOverText.text = ""; //setting the text blank here
rigidbody = GetComponent<Rigidbody2D>();
rigidbody.velocity = Vector2.up * speed;
GameObject soundControllerObject = GameObject.FindWithTag("SoundController");
if (soundControllerObject != null)
{
soundController = soundControllerObject.GetComponent<SoundControllerScript>();
}
else
{
Debug.Log("Cannot find 'SoundController' object");
}
}
float hitFactor(Vector2 ballPos, Vector2 racketPos, float racketWidth)
{
return (ballPos.x - racketPos.x) / racketWidth;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Racket")
{
//calculate hit factor
float x = hitFactor(transform.position,
collision.transform.position,
collision.collider.bounds.size.x);
//calculate direction, set length to 1
Vector2 direction = new Vector2(x, 1).normalized;
//set Velocity with direction * speed
rigidbody.velocity = direction * speed;
soundController.BallHitsRacketSound();
}
}
public void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "OutOfBoundsTrigger") {
gameOver.text = "Game Over"; //setting the text to Game Over here
soundController.BallHitsRacketSound();
}
}
}
Here is the Ball prefab showing that GameOverText has been dragged onto it.
And here’s the hierarchy showing that both the Ball prefab and GameOverText prefab are in the scene: