Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Unity + NGUI 實現聊天系統(循環加載篇)

編輯:關於 Android 程式設計

用 NGUI 做聊天系統,最偷懶的方式是照搬 Example12 裡的 TextList。但一個 UILabel 撐起的聊天界面擴展性太差,想加特殊的點擊事件更是痛苦。

更合理的做法是:一個 UIScrollView 下掛一個 UITable,把 UILabel 和其他元素封裝成 Prefab,逐條加載進 UITable。如果不考慮其他約束,這就是一個普通的 UIScrollView,沒什麼難度。

但真實項目裡有兩個硬骨頭:一是圖文混排,二是循環加載。 世界頻道這種場景,每個玩家都能發言,輕鬆上百條,不可能每條數據都實例化一個 Prefab。本文只聚焦第二點。

標準循環加載的前提

循環加載的思路是:在可顯示範圍內,用盡可能少的 Prefab,通過改變裡面的數據來呈現不同內容,而不是為每條數據都實例化對象。

NGUI 官方教程中的做法是 UIScrollView 下掛 UIGrid,UIGrid 下掛 Prefab,且每個 Prefab 高度一致。只有滿足這個前提,才能準確算出:最少需要多少個 Prefab、當前滑到哪一個、每個 Prefab 該填什麼數據。

而聊天系統恰恰不滿足:每個人發的話字數不同,每個 UILabel 高度也就不同。基於高度的種種計算全部失效,原有的循環加載邏輯必須改造。

改造思路

第一步,把 UIGrid 換成 UITable。 因為 UITable 不要求每一行的間距統一。

第二步,寫一個繼承 UIScrollView 的類,本文命名為 CUIChatScrollView。

標準循環加載需要知道三件事:最多同屏顯示多少條、總共多少數據、每個 Prefab 多高。最優方案是:同屏 6 條就只實例化 7 個。但高度不確定時,這個方案用不了。

於是我們換一種判斷方式:

· 不再依賴邊框計算,改用上下兩個臨界值。 實例化一個預估數量的 Prefab 池,當某個 Prefab 越過臨界值時就把它移到另一邊。
· 不再用位置比例算索引,改用自增自減維護。 把頂部的 Prefab 移到底部就 index++,把底部的移到頂部就 index--。
· 目標位置不再靠固定間距推算,改用 NGUI 提供的測量能力。 先把文字塞進 UILabel,通過 NGUIMath.CalculateRelativeWidgetBounds() 算出它的實際高度,再加上下一個 Prefab 的坐標來確定新位置。

具體取值上,項目中上下最多同時可見 3 條,但為了循環加載需要預留,實際實例化 10 個 Prefab。若每句話只有一行,我的行高是 25 像素,上下臨界值就設為 250。(這些數字都還可以進一步調優,此處只是示意。)

核心代碼

using UnityEngine;
using System.Collections.Generic;

public class CUIChatScrollView : UIScrollView
{
    public delegate void OnMoveCallBack();
    /// <summary>
    /// 每次滑動結束的回調
    /// </summary>
    public OnMoveCallBack mOnMoveCallback;

    public delegate void OnMoveNextPage(int pageindex);
    public OnMoveNextPage mOnMoveNextPage;

    private float mTopOffSetValue = 250;
    private float mBottomOffSetValue = 250;

    /// <summary> 當前數據總數 </summary>
    private int mTotalCount = 0;

    /// <summary> 子物體當前臨時坐標 </summary>
    private float mTempPosition = 0;

    /// <summary>
    /// 子物體當前臨時相對坐標(與 UIPanel 偏移、DynamicComponentTran、
    /// 自身坐標之和;若裁剪區域有偏移,還需加上 UIPanel finalClipRegion 的偏移)
    /// </summary>
    private float mBorderValue = 0;

    /// <summary> 當前顯示出來的物體列表 </summary>
    private List<CBaseComponent> mCurrentComList = new List<CBaseComponent>();

    /// <summary> 達到臨界值需要移動的臨時列表 </summary>
    private List<CBaseComponent> mTempComList = new List<CBaseComponent>();

    /// <summary> components 的父物體,即 UIPanel 的子物體 </summary>
    private Transform DynamicComponentTran;

    /// <summary> 當前 ScrollView 依賴的 UIPanel </summary>
    private UIPanel mUIPanel;

    /// <summary> UIPanel 最終的繪制區域、坐標 </summary>
    private Vector4 mPanelFinalClipRegion;

    /// <summary> 是否需要請求下一頁數據(分頁加載場景) </summary>
    private bool bNeedReqNextPage;

    /// <summary> 每頁數量 </summary>
    private int mPrePageNumber;

    /// <summary> 是否是排行榜模式 </summary>
    private bool bIsRankModel;

    /// <summary> 當前自己的排名 </summary>
    private int mCurrentMyRank;

    /// <summary> 緩存開關 </summary>
    private Dictionary<int, bool> bHasRequestDic = new Dictionary<int, bool>();

    private float xPos;
    private float yPos;

    /// <summary> 是否需要 3D 顯示效果 </summary>
    private bool bShow3DStyle = false;

    /// <summary> 居中的子物體 </summary>
    public Transform mCenterTranform;

    private int mUIPanelDepth = 1;
    private int m_Index = 0;
    private int m_maxShowNum = 0;

    public void Init<T>(List<T> components, int maxShowNum, int totalNumber,
            Transform dyTransorm, Movement moveMent = Movement.Horizontal,
            bool needrequest = false, int prepagenum = 0, bool isrank = false,
            int myrank = 0, bool bshow3d = false) where T : CBaseComponent
    {
        m_Index = maxShowNum - 1;
        m_maxShowNum = maxShowNum;
        mCurrentComList.Clear();
        for (int i = 0, length = components.Count; i < length; i++)
        {
            if (components[i] is CBaseComponent)
            {
                mCurrentComList.Add(components[i]);
            }
        }
        DynamicComponentTran = dyTransorm;
        mTotalCount = totalNumber;
        movement = moveMent;
        mPanelFinalClipRegion = (mUIPanel ?? (mUIPanel = gameObject.GetComponent<UIPanel>())).finalClipRegion;
        // 子物體固定高出父物體 10 個深度單位
        mUIPanelDepth = mUIPanel.depth + 10;
        bNeedReqNextPage = needrequest;
        mPrePageNumber = prepagenum;
        bIsRankModel = isrank;
        mCurrentMyRank = myrank;
        bHasRequestDic.Clear();
        bShow3DStyle = bshow3d;
        momentumAmount = 35f;
    }

    public override void MoveRelative(Vector3 relative)
    {
        base.MoveRelative(relative);
        CheckScrollView(relative);
    }

    public override void AdjustSpring(Vector3 relative)
    {
        base.AdjustSpring(relative);
        CheckScrollView(relative);
    }

    private void CheckScrollView(Vector3 relative)
    {
        if (mCurrentComList == null || mCurrentComList.Count == 0) return;

        if (movement == Movement.Horizontal)
        {
            xPos = relative.x;
            mCurrentComList.Sort(delegate (CBaseComponent a, CBaseComponent b)
            {
                return a.LocalPosition.x.CompareTo(b.LocalPosition.x);
            });
        }
        else if (movement == Movement.Vertical)
        {
            yPos = relative.y;
            mCurrentComList.Sort(delegate (CBaseComponent a, CBaseComponent b)
            {
                return b.LocalPosition.y.CompareTo(a.LocalPosition.y);
            });
        }

        mTempComList.Clear();

        // 向下滑動:頂部的越過上臨界值,移到底部
        if ((yPos > 0 && movement == Movement.Vertical)
                || (xPos < 0 && movement == Movement.Horizontal))
        {
            Transform temptran = mCurrentComList[mCurrentComList.Count - 1].ComTransform;
            mTempPosition = (movement == Movement.Horizontal)
                    ? temptran.localPosition.x : temptran.localPosition.y;
            mTempPosition = Mathf.Abs(mTempPosition);

            for (int i = 0, j = mCurrentComList.Count; i < j; i++)
            {
                temptran = mCurrentComList[i].ComTransform;
                if (movement == Movement.Horizontal)
                {
                    mBorderValue = (temptran.localPosition.x * temptran.localScale.x
                            + transform.localPosition.x
                            + DynamicComponentTran.localPosition.x
                            + Mathf.Abs(mPanelFinalClipRegion.x));
                    if (mBorderValue > -mTopOffSetValue) break;
                }
                else if (movement == Movement.Vertical)
                {
                    mBorderValue = (temptran.localPosition.y * temptran.localScale.y
                            + transform.localPosition.y
                            + DynamicComponentTran.localPosition.y
                            + Mathf.Abs(mPanelFinalClipRegion.y));
                    if (mBorderValue < mTopOffSetValue) break;
                }
                mTempComList.Add(mCurrentComList[i]);
            }

            for (int i = 0, j = mTempComList.Count; i < j; i++)
            {
                if (m_Index >= mTotalCount - 1) break;
                m_Index++;
                mTempComList[i].InitData(m_Index);
                if (movement == Movement.Vertical)
                {
                    // 用 NGUI 測量真實高度,而非依賴固定間距
                    float spriteHeight = NGUIMath.CalculateRelativeWidgetBounds(
                            transform, mCurrentComList[mCurrentComList.Count - 1].ComTransform, true).size.y;
                    mTempComList[i].LocalPosition = new Vector3(0, -(spriteHeight + mTempPosition), 0);
                }
            }
        }
        // 向上滑動:底部的越過下臨界值,移到頂部
        else if ((yPos < 0 && movement == Movement.Vertical)
                || (xPos > 0 && movement == Movement.Horizontal))
        {
            Transform temptran = mCurrentComList[0].ComTransform;
            mTempPosition = (movement == Movement.Horizontal)
                    ? temptran.localPosition.x : temptran.localPosition.y;
            mTempPosition = Mathf.Abs(mTempPosition);

            for (int i = mCurrentComList.Count - 1; i >= 0; i--)
            {
                temptran = mCurrentComList[i].ComTransform;
                if (movement == Movement.Horizontal)
                {
                    mBorderValue = (temptran.localPosition.x
                            + transform.localPosition.x
                            + DynamicComponentTran.localPosition.x
                            + Mathf.Abs(mPanelFinalClipRegion.x));
                    if (mBorderValue < -mBottomOffSetValue) break;
                }
                else if (movement == Movement.Vertical)
                {
                    mBorderValue = (temptran.localPosition.y
                            + transform.localPosition.y
                            + DynamicComponentTran.localPosition.y
                            + Mathf.Abs(mPanelFinalClipRegion.y));
                    if (mBorderValue > -mBottomOffSetValue) break;
                }
                mTempComList.Add(mCurrentComList[i]);
            }

            for (int i = 0, j = mTempComList.Count; i < j; i++)
            {
                if (m_Index <= m_maxShowNum - 1) break;
                m_Index--;
                mTempComList[i].InitData(m_Index - m_maxShowNum + 1);
                if (movement == Movement.Vertical)
                {
                    float spriteHeight = NGUIMath.CalculateRelativeWidgetBounds(
                            transform, mTempComList[i].ComTransform, true).size.y;
                    Vector3 newPosition;
                    if (i == 0)
                        newPosition = new Vector3(0, -(mTempPosition - spriteHeight), 0);
                    else
                        newPosition = new Vector3(0,
                                -(Mathf.Abs(mTempComList[i - 1].LocalPosition.y) - spriteHeight), 0);
                    mTempComList[i].LocalPosition = newPosition;
                }
            }
        }

        if (mOnMoveCallback != null)
        {
            mOnMoveCallback();
        }
    }
}

小結

高度不確定時,循環加載的核心轉變有三點:把「按邊框精確計算」換成「按臨界值粗略判斷」,把「按位置比例算索引」換成「按移動方向增減索引」,把「按固定間距推位置」換成「按實際測量結果定位置」。這樣一来,聊天場景下任意高度的文本條目都能被同一套邏輯正確地循環複用。

代碼裡預留了分頁請求(bNeedReqNextPage)、排行榜模式(bIsRankModel)、3D 展示等擴展點,實際項目中可按需接入。圖文混排部分則建議通過自定義富文本組件,配合 NGUI 的 UITexture 與 UILabel 混合排布來實現,本文不再展開。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved