Ant*_*ans 1 c# unity-game-engine
因此,我正在尝试在Unity中的文本元素上添加OnclickEvent。(UnityEngine.UI.Text)但是Text对象没有onclick事件处理程序。我很确定这是可能的,否则Unity应该是无法单击文本对象的第一语言。我已经找到
您不能,至少不能直接。使用OnGUI绘制的GUIText无法检测到输入,您必须使用GUI按钮。但是您根本不应该使用OnGUI。新的Unity UI系统是在几个月前发布的,它非常优越。您应该更新到Unity 4.6.3,然后开始使用它。 无法添加onclick事件
但是我只是无法想象它不可能点击文本。出于布局原因,我真的不想使用按钮。
谢谢
您只需使用IPointerClickHandler界面和一个即可创建自己的点击处理程序UnityEvent:
public class TextButton : MonoBehaviour, IPointerClickHandler
{
// add callbacks in the inspector like for buttons
public UnityEvent onClick;
public void OnPointerClick(PointerEventData pointerEventData)
{
//Output to console the clicked GameObject's name and the following message. You can replace this with your own actions for when clicking the GameObject.
Debug.Log(name + " Game Object Clicked!", this);
// invoke your event
onClick.Invoke();
}
}
Run Code Online (Sandbox Code Playgroud)
确保
EventSystem场景中存在,以允许单击检测。要在非UI GameObjects上进行点击检测,请确保将PhysicsRaycaster附加到Camera。
或者,您可以使用该EventTrigger组件。
两者基本上都会或多或少地做同一件事:
第一个的巨大优点是您可以轻松地对其进行增强,例如,通过视觉反馈,例如更改按钮的颜色:
[RequireComponent(typeof(Text))]
public class TextButton : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler
{
#region Inspector
public Color NormalColor = Color.black;
public Color HoverColor = Color.black;
public Color PressColor = Color.black;
public Color DisabledColor = Color.gray;
// add callbacks in the inspector like for buttons
public UnityEvent onClick;
#endregion Inspector
private bool _isInteractive = true;
public bool interactive
{
get
{
return _isInteractive;
}
set
{
_isInteractive = value;
UpdateColor();
}
}
private bool _isPressed;
private bool _isHover;
private Text _textComponent;
private Text TextComponent
{
get
{
if(!_textComponent) _textComponent = GetComponent<Text>() ?? gameObject.AddComponent<Text>();
}
}
private void Updatecolor()
{
if (!interactive)
{
TextComponent.color = DisabledColor;
return;
}
if (isPressed)
{
TextComponent.color = PressColor;
return;
}
if (isHover)
{
TextComponent.color = HoverColor;
return;
}
TextComponent.color = NormalColor;
}
#region IPointer Callbacks
public void OnPointerClick(PointerEventData pointerEventData)
{
//Output to console the clicked GameObject's name and the following message. You can replace this with your own actions for when clicking the GameObject.
Debug.Log(name + " Game Object Clicked!", this);
// invoke your event
onClick.Invoke();
}
public void OnPointerDown(PointerEventData eventData)
{
if(!_isHover)return;
_isPressed = true;
Updatecolor();
}
public void OnPointerUp(PointerEventData eventData)
{
if(!_isHover)return;
_isPressed = false;
Updatecolor();
}
public void OnPointerEnter(PointerEventData eventData)
{
_isHover = true;
Updatecolor();
}
public void OnPointerExit(PointerEventData eventData)
{
_isHover = false;
_isPressed = false;
Updatecolor();
}
#endregion IPointer Callbacks
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |