Button doesnt work after reactivating Canvas.

Hello,

I’m creating a Tower Defense game where the player acts as a tower. The problem that I have is when a canvas is activated after some enemies getting to the end of the maze, which shows a “GAME OVER” text and a button that takes the player back to the main menu scene. But even though I have the scene loading script attached to the button and have EventSystem in place, the button doesn’t seem to respond to the mouse press. Also at the same time, the cursor disappears and I need to click Esc every time after pressing the button to see the cursor again. I’ve tried to see if there is something inherently wrong with the button/canvas by creating a temporary scene and pasting it, but everything worked perfectly there.

Thanks in advance for any advice.

did you add the scene to the build settings?

Here attach this script to a GameObject in your hierarchy and click on the button.

It debugs the first thing that it hits on. The problem may have occured cause of something that is lying above your button.

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class UIObjectDetector : MonoBehaviour
{
	public static UIObjectDetector instance;
	public EventSystem es;
	public PointerEventData ped;
	public List<RaycastResult> rr;
	public bool debug;
	
	void Awake ()
	{
		instance = this;
	}
	void Start ()
	{
		ped = new PointerEventData (null);
		rr = new List<RaycastResult> ();
	}
	public void Update ()
	{
		if (Input.GetMouseButtonDown (0) && debug) {
			IsOverUIObject ();
		}
	}

    public bool IsOverUIObject ()
	{
		ped.position = Input.mousePosition;
		rr.Clear ();

		es.RaycastAll (ped, rr);
		if (rr.Count != 0) {
            Debug.Log("Object Clicked on " + rr[0].gameObject.name + " Parent is " + rr[0].gameObject.transform.parent.name);
            if (rr [0].gameObject.layer == LayerMask.NameToLayer ("UI")) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
}

If that’s not the problem, check if your button has Image attached to it and that its RaycastTarget property is checked.


Hope this Helps!

The problem is that after transitioning from the first-person camera to another camera( I use the second one for a player to be able to set position to which he can teleport) and then reactivate it along with the canvas where the game over is shown, the button doesn’t even react to the mouse, and the mouse itself is not showing until I use Esc key, even though it’s displayed for the first time. kodi

Okay, it started detecting the button when I pressed the Esc key when the camera on my player was still active(along with the entire player). When I did that, the mouse persisted to the next camera and the event system started recognizing stuff I was hovering over. Still, there is a problem of making the cursor active before the transition.