How to create a hover effect through C Sharp code.

Hello, I’m a student game dev and I need help with the hover features in one of my games. I’ve tried to implement some makeshift keyboard controls using code I understand… void Update() { //Up arrow is pressed if (Input.GetKey(KeyCode.UpArrow)) { MenuS = 0; } // Down arrow is pressed if (Input.GetKey(KeyCode.DownArrow)) { MenuS = 1; } // Enter key is pressed if (Input.GetKeyDown(KeyCode.Space) && MenuS == 0) { SceneManager.LoadScene("level_01"); print("Enter is pressed on start"); } if (Input.GetKeyDown(KeyCode.Space) && MenuS == 1) { Application.Quit(); print("Quit"); }

Because I only have two possible buttons (Play game and quit game) I’ve decided to use this code. This code works, the only problem is there is no effects for the player to tell what button they have selected. I was hoping someone could tell me how to program the hover effects that I use for my button into code so that whenever Menus=0 the start button would be highlighted with the preset hover effects I already have set in Unity.

two ways:


create a highlight image and parent it to each of the buttons. After selecting the index of the button, find SetActive(true) on the hightlight-gameObject. SetActive(false) on all the other objects.


Create a monobhehavior script, and make it inherit not only from Monobehavior, but also from IpointerEnterhandler

Attach monobehavior to your button

This will force you to specify a function void OnPointerEnter(). It will be automatically called by unity whenever a UI element (a gameObject) with this script (and with an image) gets a cursor hover over it. Use this function to perform any highlighting to the button its attached to.

Recall, you can get refrence tot he gameObject from the script its attached to by this.gameObject and a reference to the button like


Recall that UI elements require you to add using UnityEngine.UI; and to use the IPointerEnterHandler, you need to connect another block of code with using UnityEngine.EventSystems;

Of course, there is also IPointerExitHandler, which can be used to stop the highlighting.