[英]How to Make a Clickable Sprite in Unity 2D, detect if the cursor is hovering over a sprite, and how to change scene with code
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我正在统一制作 2D 游戏,我想要一个开始屏幕,但我无法找到如何让开始按钮可点击,然后将场景更改为 1 级
The game will be a cursor labyrinth, so any help with detecting if a mouse is hovering over something would be appreciated游戏将是一个 cursor 迷宫,所以任何帮助检测鼠标是否悬停在某物上的帮助将不胜感激
I looked up a bunch of tutorials but none of them worked in c#我查了一堆教程,但没有一个适用于 c#
STEP 1:第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.或者,您可以右键单击 Scene Hierarchy 和 go 以创建 -> UI -> 按钮。 This automatically creates a simple Button for you.
这会自动为您创建一个简单的 Button。 Then it sprites can be changed accordingly.
然后它的精灵可以相应地改变。
STEP 2:第2步:
Then assign callback to the Button in the OnClick() Field to make it interactable.然后将回调分配给 OnClick() 字段中的按钮,使其可交互。 To load the scene, Create a new C# script.
要加载场景,请创建一个新的 C# 脚本。 Make a new method in it.
在其中创建一个新方法。 Use the LoadScene method in SceneManagement class. Then the script becomes:
使用SceneManagement class中的LoadScene方法。那么脚本就变成了:
using UnityEngine;
using UnityEngine.SceneManagement;
public class ExampleScript: MonoBehaviour
{
public void Loadscene(int sceneIndex)
{
SceneManager.LoadScene(sceneIndex);
}
}
Here you go bro.给你 go 兄弟。
public bool IsOverUi() { var eventDataCurrentPosition = new PointerEventData(EventSystem.current) { position = Input.mousePosition };
public bool IsOverUi() { var eventDataCurrentPosition = new PointerEventData(EventSystem.current) { position = Input.mousePosition }; var results = new List();
var results = new List(); EventSystem.current.RaycastAll(eventDataCurrentPosition, results);
EventSystem.current.RaycastAll(eventDataCurrentPosition, 结果); return results.Count > 0;
返回结果.Count > 0; }
}
Following the Answer here: https://answers.unity.com/questions/1199251/onmouseover-ui-button-c.html按照这里的答案: https://answers.unity.com/questions/1199251/onmouseover-ui-button-c.html
You can add a script:您可以添加一个脚本:
public class MyClass: MonoBehaviour, IPointerEnterHandler{
public void OnPointerEnter(PointerEventData eventData)
{
//do stuff
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.