Home > Enterprise >  How to Make a Clickable Sprite in Unity 2D, detect if the cursor is hovering over a sprite, and how
How to Make a Clickable Sprite in Unity 2D, detect if the cursor is hovering over a sprite, and how

Time:01-09

I am making a 2D game in unity, and I want a start screen, but I cant find out how to make the start button clickable, and to then change the scene to level 1

The game will be a cursor labyrinth, so any help with detecting if a mouse is hovering over something would be appreciated

I looked up a bunch of tutorials but none of them worked in c#

CodePudding user response:

STEP 1:

You will have to add a Button Component to the sprite.

Alternatively, you can right click in the Scene Hierarchy and go to Create -> UI -> Button. This automatically creates a simple Button for you. Then it sprites can be changed accordingly.

STEP 2:

Then assign callback to the Button in the OnClick() Field to make it interactable. To load the scene, Create a new C# script. Make a new method in it. Use the LoadScene method in SceneManagement class. Then the script becomes:

using UnityEngine;
using UnityEngine.SceneManagement;

public class ExampleScript: MonoBehaviour
{
    public void Loadscene(int sceneIndex)
    {
        SceneManager.LoadScene(sceneIndex);
    }
}

CodePudding user response:

Here you go bro.

public bool IsOverUi() { var eventDataCurrentPosition = new PointerEventData(EventSystem.current) { position = Input.mousePosition }; var results = new List(); EventSystem.current.RaycastAll(eventDataCurrentPosition, results); return results.Count > 0; }

  • Related