克劳萨尔,你要找的是......
一个按钮 (!!!)
就是这么简单!
-
单击“添加画布”。 (您很可能想要“缩放到屏幕尺寸” - 选择该选项。)
-
单击“添加按钮”。
-
没有“三”..去喝酒吧。
在您的代码中,为右侧按钮设置这样的例程
public void UserClickedRight()
{
Debug.Log("click right whoo!");
}
左侧按钮也有类似的例程。
1. 前往您的Button
在编辑器中。
2. 只需将脚本拖到其中并选择UserClickedRight
!!
实际上,您不必从头开始对按钮进行编程:)
这是 Unity 的基本机制 - 将游戏对象拖到编辑器中的“槽”中。
(您拖动的游戏对象上有相关脚本。)
您无需进入触摸处理级别即可实现按钮!
现在你问,“按住按钮时”怎么样?
这非常简单,您只需要了解有关 Unity“事件”系统的一些知识即可。
In Button
,Unity已经完成了“OnClick”的所有工作:
由于“点击”很常见,因此为了方便起见,他们将其放在“检查器”面板中。
好消息是Button
has 您可以使用更多事件.
http://docs.unity3d.com/ScriptReference/UI.Button.html
我猜你想用OnPointerDown
and OnPointerUp
在你的情况下。
要使用其他事件(Unity 没有费心将其放入检查器面板中)非常简单,您只需
1,制作一个引用您想要的事件的脚本,
and,
2,你将该脚本放在有问题的按钮上......
就是这么简单。
逐步解释:
您将使用 Unity 的事件系统,因此:
using UnityEngine.EventSystems;
下一个。你知道脚本通常是这样开始的......
public class FancyButton:MonoBehaviour
“MonoBehaviour”部分仅意味着它是一个将“驱动游戏对象”的 C# 脚本。
在这种情况下,我们必须进一步提醒引擎您将使用这些点击事件。所以你添加这个。
,IPointerDownHandler,IPointerUpHandler
到目前为止我们有这个
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
现在是简单的部分。
您只需输入 Unity 将为您运行的两个例程,当这些事情发生时。
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
public void OnPointerDown(PointerEventData data)
{
Debug.Log("holy! someone put the pointer down!")
}
public void OnPointerUp(PointerEventData data)
{
Debug.Log("whoa! someone let go!")
}
}
现在您所要做的就是将该脚本放到按钮上。完毕!
您可以将该脚本放在任何需要该功能的按钮上。
接下来,单击 Obi-wan 查看我们目前所处的位置!
最后,听起来您想要“当按住按钮时”做某事。这只是一个一般的编程问题 -你有一个布尔值,当按钮向上和向下移动时打开和关闭它。我们开始做吧。
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
[System.NonSerialized] public bool mouseIsDownRightNow;
public void OnPointerDown(PointerEventData data)
{
mouseIsDownRightNow = true;
}
public void OnPointerUp(PointerEventData data)
{
mouseIsDownRightNow = false;
}
}
您可以从另一个脚本或您想要的任何内容访问该变量。
如果您想在按钮按下时运行例程,请添加以下内容:
void Update()
{
if (buttonIsDownRightNow) WhileButtonIsDown();
}
private void WhileButtonIsDown()
{
Debug.Log("THE BUTTON IS DOWN! WHOA!");
}
尝试一下,并在按住按钮时观察控制台。
这是一个在按钮按下时不断增加值的示例:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class FancyButton:MonoBehaviour,IPointerDownHandler,IPointerUpHandler
{
[System.NonSerialized] public bool buttonIsDownRightNow;
private int countSomething;
public void OnPointerDown(PointerEventData data)
{
buttonIsDownRightNow = true;
}
public void OnPointerUp(PointerEventData data)
{
buttonIsDownRightNow = false;
}
private void WhileButtonIsDown()
{
++countSomething;
}
void Update()
{
if (buttonIsDownRightNow) WhileButtonIsDown();
Debug.Log("value is now " +countSomething.ToString());
}
}
这里的所有都是它的。一旦您真正了解了 Unity 中的事件,就无需了解更多 Unity 了。
唯一的其他重要主题是 Mecanim、着色器编写、触摸、协程、线程、PhysX、本机插件、精灵、网络、动态网格、导航、VR、AR、动画、逆运动学、粒子、地形、IAP、照明、烘焙、阴影、MMP、角色控制器和音频。享受!