Why doesn't Event Trigger work in unity 2d?

Viewed 2653

I have created a UI Button in unity 2d and it works fine. But I think the event trigger component doesn't work. I want to make the button bigger when the cursor is on the button and return to normal size when the cursor exits it. Here is my script...

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayAgainButton : MonoBehaviour
{
    public void PointerEnter()
    {
        Debug.Log("Enter");
        transform.localScale = new Vector2(1.2f, 1.2f);
    }

    public void PointerExit()
    {
        Debug.Log("Exit");
        transform.localScale = new Vector2(1f, 1f);
    }

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

When I play the game, the Console says that the cursor has entered and exited

Console

But the scale of the button never changes.

What is wrong here?

3 Answers

You need to add the event system. Try like this.


using UnityEngine;
using UnityEngine.EventSystems;

public class ButtonTest : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("Enter");
        this.transform.localScale = new Vector2(1.2f, 1.2f);
    }



    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("Exit");
        this.transform.localScale = new Vector2(1f, 1f);
       
    }
}       
    
 

Set your handle mode in scene to canvas mode with the T key of the keyboard. Key w,e,r,t are to manipulate position, rotation, scale and canvas respectively. You will see the blue circles in the corners with which you will be able to set the size.

Check making that bigger to get your events triggered. For the button component case, the area of effect is determined by the canvas size. This might also be the case.

  1. Check if your Button is in a layout - layouts will set the size and overwrite the changes you do in code.
  2. Button probably uses RectTransform (as it's a UI Element) so you could try setting localScale of that.
Related