HI! I’m running 3 scripts, one is on the player object, another on a “controller” empty object I have for various tasks, and another in my canvas, but I’ll talk about that one in a moment. In this case, I want to make a “game over” function where I set the timescale to 0.
This is on the player character:
public class PlayerScript : MonoBehaviour
{
public float rotationSpeed;
private GameObject playerPivot;
public GameObject target;
public CanvasScript canvas;
public bool isCollidingWithTarget = false;
public KeyCode Spacebar = KeyCode.Space;
public bool isSpacebarPressed = false;
{
playerPivot = GameObject.Find("Player Pivot");
target = GameObject.Find("Target");
}
void Update()
{
playerPivot.transform.Rotate(0, 0, rotationSpeed*Time.deltaTime);
if (Input.GetKeyDown(Spacebar))
{
rotationSpeed *=- 1;
isSpacebarPressed = true;
if (isCollidingWithTarget==true)
{
target.GetComponent<TargetScript>().ChangePosition();
canvas.AddScore();
}
}
else
{
isSpacebarPressed = false;
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject == target)
{
isCollidingWithTarget = true;
Debug.Log("enters");
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject == target)
{
isCollidingWithTarget = false;
Debug.Log("exits");
}
}
}
Basically my player object is a rectangle that spins on a pivot (a parent that is an empty game object on 0x,0y) and changes position when I press the spacebar, a target appears somewhere random in the circumference and you have to tap the key when the player reaches it, it checks if the rectangle has entered the trigger , which sets a bool called “isCollidingWithTarget” to “true” and when it exits the the same trigger it sets it to “false” and so on.
I’m trying to make a failstate when you miss the target, but Here’s the problem…
I want to make a function in my “controller” script, something like
void GameOver()
{
Time.timeScale = 0f;
}
And I want to call it in my third script that I have in my Canvas called “CanvasScript” right here:
if (player.GetComponent<PlayerScript>().isCollidingWithTarget==false && player.GetComponent<PlayerScript>().isSpacebarPressed==true)
{
GameOverText();
}
I already have a GameOver() function in my CanvasScript, but it’s for the game over text that appears when you miss the target (it does that by turning on a TextMeshProUGUI on that already has “Game Over” written on it).
It looks like this:
public void GameOverText()
{
gameOverScreen.SetActive(true);
}
Is there a way to do that?
I know I could just put it on my CanvasScript but I’d like to keep things organized and not to have a very important function on my UI script.
Btw, sorry if this post is super long, it’s my first one.