有没有一种在Unity中创建简单的2D按钮而不使用UI层的方法。我有一个有很多按钮的游戏,我不想将整个应用程序制作成UI。欢迎添加更多控件:开关、滑块等。
PS.我看到了NGUI,但到目前为止我不喜欢它。还有其他选择吗?
PS.我看到了NGUI,但到目前为止我不喜欢它。还有其他选择吗?
Sprite
/Sprite Render
作为 Button
。首先创建一个游戏对象,并将 EventSystem
和 StandaloneInputModule
添加到它上面。将 Physics2DRaycaster
添加到相机上,实现 IPointerClickHandler
并重写 OnPointerClick
函数。通过前往GameObject->2D Object->Sprite 创建 2D 精灵,然后将脚本附加到精灵上。以下是完成此操作的完整代码:using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections;
public class SPRITEBUTTON: MonoBehaviour, IPointerClickHandler,
IPointerDownHandler, IPointerEnterHandler,
IPointerUpHandler, IPointerExitHandler
{
void Start()
{
//Attach Physics2DRaycaster to the Camera
Camera.main.gameObject.AddComponent<Physics2DRaycaster>();
addEventSystem();
}
public void OnPointerClick(PointerEventData eventData)
{
Debug.Log("Mouse Clicked!");
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log("Mouse Down!");
}
public void OnPointerEnter(PointerEventData eventData)
{
Debug.Log("Mouse Enter!");
}
public void OnPointerUp(PointerEventData eventData)
{
Debug.Log("Mouse Up!");
}
public void OnPointerExit(PointerEventData eventData)
{
Debug.Log("Mouse Exit!");
}
//Add Event System to the Camera
void addEventSystem()
{
GameObject eventSystem = null;
GameObject tempObj = GameObject.Find("EventSystem");
if (tempObj == null)
{
eventSystem = new GameObject("EventSystem");
eventSystem.AddComponent<EventSystem>();
eventSystem.AddComponent<StandaloneInputModule>();
}
else
{
if ((tempObj.GetComponent<EventSystem>()) == null)
{
tempObj.AddComponent<EventSystem>();
}
if ((tempObj.GetComponent<StandaloneInputModule>()) == null)
{
tempObj.AddComponent<StandaloneInputModule>();
}
}
}
}
编辑:
如果这是一个3D游戏对象/网格,则需要向其添加一个简单的碰撞器。如果它只是一个精灵,则必须向该精灵添加2D碰撞器。
另一种更简单的方法是只需添加一个BoxCollider2D组件,然后将以下方法添加到新组件(例如UIButton)中,以执行按钮操作:
这样就避免了使用EventSystem、StandaloneInputModule和Physics2DRaycaster。
示例:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class UIButton : MonoBehaviour {
public Sprite regular;
public Sprite mouseOver;
public Sprite mouseClicked;
public TextMeshPro buttonText;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
private void OnMouseDown()
{
}
private void OnMouseEnter()
{
}
private void OnMouseExit()
{
}
private void OnMouseUpAsButton()
{
}
}
此代码在Unity 2018.1中进行了测试。与上述方法相比,我最初注意到的一个区别是,在此模型中无法检测到鼠标右键单击事件,但可以在EventSystemModel中检测到。