版权声明:文章均是博主原创,如需转载,请在文章开头注明出处和署名! https://blog.csdn.net/shirln/article/details/85260384
推荐阅读:
UGUI的简介:
UGUI系统是从Unity 4.6开始,被集成到Unity的编辑器中Unity官方给这个新的UI系统赋予的标签是:灵活,快速和可视化!,简单来说对于开发者而言就是有三个优点:效率高效果好,易于使用,扩展,以及与Unity的兼容性高。
在不使用任何代码的前提下,就可以简单快速额在游戏中建立其一套UI界面,这在过去是绝对不可想想的,但是新的UI系统确实做到了这一点因为Unity预定义了很多常见的组件,它们以“游戏对象”的形式存在于游戏场景中。
在前文中我们已经通过一系列案例掌握了UGUI的使用,下面我们最后再来巩固一下。
下面我们再举个关卡分页设计例子,综合理解UGUI
实现直接滑动
设置通过添加组件设置内容的滑动,多余内容的隐藏
实现点击下面的圆圈滑动
主要代码:
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class LevelButtonScrollRect : MonoBehaviour ,IBeginDragHandler,IEndDragHandler
{
private ScrollRect scrollRect;
public float smoothing = 4; //插值的速度
private float[] pageArray=new float[]{ 0,0.33333f,0.66666f,1 }; //每个页面X轴坐标
private float targetHorizontalPosition=0; //距离最近页面的X坐标
private bool isDraging = false; //是否拖拽的标志位
public Toggle[] toggleArray; //圆圈数组
void Start ()
{
scrollRect = GetComponent<ScrollRect>();
}
void Update ()
{
if(isDraging==false)
scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition,
targetHorizontalPosition, Time.deltaTime*smoothing);
}
public void OnBeginDrag(PointerEventData eventData)
{
isDraging = true;
}
public void OnEndDrag(PointerEventData eventData)
{
isDraging = false;
//找到当前位置与每页距离最小的页面,并切换到该页面
float posX = scrollRect.horizontalNormalizedPosition;
int index = 0;
float offset = Mathf.Abs(pageArray[index] - posX);
for (int i = 1; i < pageArray.Length; i++)
{
float offsetTemp = Mathf.Abs(pageArray[i] - posX);
if (offsetTemp < offset)
{
index = i;
offset = offsetTemp;
}
}
targetHorizontalPosition = pageArray[index];
toggleArray[index].isOn = true;
//scrollRect.horizontalNormalizedPosition = pageArray[index];
}
public void MoveToPage1(bool isOn) {
if (isOn)
{
targetHorizontalPosition = pageArray[0];
}
}
public void MoveToPage2(bool isOn) {
if (isOn) {
targetHorizontalPosition = pageArray[1];
}
}
public void MoveToPage3(bool isOn) {
if (isOn)
{
targetHorizontalPosition = pageArray[2];
}
}
public void MoveToPage4(bool isOn) {
if (isOn)
{
targetHorizontalPosition = pageArray[3];
}
}
}
说明:由于编辑器操作比较复杂,文字描述可能会让读者存在疑惑,因此我采用图片解说方式向大家展示。如果对于这个方式有什么意见或建议欢迎留言~
通过上面操作,你已经对UGUI有了更深入的了解,如果有什么疑惑欢迎评论区留言。最后告诉你一个小秘密,学习unity一定要亲自操作编辑器哦!