本文实例为大家分享了UGUI轮播图组件实现的具体代码,供大家参考,具体内容如下
要用到,于是就自已做了一个,自认为封装上还是OK的,开发于unity5.1.2。
支持自动轮播、手势切换、代码调用切换,支持水平和竖直两个方向以及正负方向轮播,轮播索引改变有回调可以用,也可以获取到当前处于正中的子元素。
要注意的是,向轮播列表中加入新元素不能直接setparent,要调用该组件的AddChild方法
下面是鄙人的代码:
/// 主要关注属性、事件及函数:
/// public int CurrentIndex;
/// public Action OnIndexChange;
/// public virtual void MoveToIndex(int ind);
/// public virtual void AddChild(RectTransform t);
/// by yangxun
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
///
/// 轮播图组件
///
[RequireComponent(typeof(RectTransform)), ExecuteInEditMode]
public class Carousel : UIBehaviour, IEventSystemHandler, IBeginDragHandler, IInitializePotentialDragHandler, IDragHandler, IEndDragHandler, ICanvasElement {
///
/// 子物体size
///
public Vector2 CellSize;
///
/// 子物体间隔
///
public Vector2 Spacing;
///
/// 方向
///
public Axis MoveAxis;
///
/// Tween时的步数
///
public int TweenStepCount = 10;
///
/// 自动轮播
///
public bool AutoLoop = false;
///
/// 轮播间隔
///
public float LoopSpace = 1;
///
/// 轮播方向--1为向左移动,-1为向右移动
///
public int LoopDir = 1;
///
/// 可否拖动
///
public bool Drag = true;
///
/// 位于正中的子元素变化的事件,参数为index
///
public Action OnIndexChange;
///
/// 当前处于正中的元素
///
public int CurrentIndex {
get {
return m_index;
}
}
private bool m_Dragging = false;
private bool m_IsNormalizing = false;
private Vector2 m_CurrentPos;
private int m_currentStep = 0;
private RectTransform viewRectTran;
private Vector2 m_PrePos;
private int m_index = 0,m_preIndex = 0;
private RectTransform header;
private bool contentCheckCache = true;
private float currTimeDelta = 0;
private float viewRectXMin {
get{
Vector3[] v = new Vector3[4];
viewRectTran.GetWorldCorners(v);
return v[0].x;
}
}
private float viewRectXMax {
get {
Vector3[] v = new Vector3[4];
viewRectTran.GetWorldCorners(v);
return v[3].x;
}
}
private float viewRectYMin {
get {