_xiaofang/xiaofang/Assets/Res/gsj/scripts/Personnelpreparation.cs
2024-12-20 10:10:19 +08:00

107 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using UnityEngine.Events;
public class Personnelpreparation : MonoBehaviour
{
private Button closeBtn;
private ScrollRect scrollView;
private List<Transform> subObjects; // 用于存储Scroll View的Content下的子物体Transform列表
// 定义一个事件,用于在子物体状态变化时触发重新排序
public UnityEvent onStatusChanged;
// Start is called before the first frame update
void Start()
{
closeBtn=transform.Find("bg/top/closeBtn").GetComponent<Button>();
closeBtn.onClick.AddListener(OnClickCloseBtn);
scrollView=transform.Find("bg/mid/Scroll View").GetComponent<ScrollRect>();
if (scrollView != null)
{
subObjects = new List<Transform>();
UpdateSubObjectList(); // 初始化时获取并存储子物体列表
// 为每个子物体的ItemInfo组件添加状态变化监听器
foreach (Transform subObject in subObjects)
{
ItemInfo itemInfo = subObject.GetComponent<ItemInfo>();
if (itemInfo != null)
{
itemInfo.statusChanged.AddListener(OnStatusChanged);
}
}
// 初始排序
SortSubObjects();
}
else
{
Debug.LogError("未正确关联 Scroll View组件请检查");
}
}
private void UpdateSubObjectList()
{
Transform contentTransform = scrollView.content;
subObjects.Clear();
// 重新遍历Content下的所有子物体更新子物体列表
for (int i = 0; i < contentTransform.childCount; i++)
{
subObjects.Add(contentTransform.GetChild(i));
}
}
private void OnStatusChanged()
{
// 当子物体状态变化时,触发重新排序
if (onStatusChanged != null)
{
onStatusChanged.Invoke();
}
}
private void SortSubObjects()
{
//使用Linq语句进行排序
subObjects = subObjects.OrderByDescending(sub => sub.GetComponent<ItemInfo>().status == "离线")
.ThenBy(sub => sub.GetComponent<ItemInfo>().status == "准备中")
.ThenBy(sub => sub.GetComponent<ItemInfo>().accountName)
.ToList();
// 按照排序后的顺序重新设置子物体在Content下的顺序
for (int i = 0; i < subObjects.Count; i++)
{
subObjects[i].SetParent(scrollView.content.transform);
subObjects[i].SetSiblingIndex(i);
}
}
// Update is called once per frame
private void Update()
{
// 在Update中监听事件若触发则重新排序
if (onStatusChanged != null && onStatusChanged.GetPersistentEventCount() > 0)
{
SortSubObjects();
onStatusChanged.RemoveAllListeners(); // 排序完成后移除监听器,避免重复触发
UpdateSubObjectList(); // 更新子物体列表,以防有新的子物体加入等情况
foreach (Transform subObject in subObjects)
{
ItemInfo itemInfo = subObject.GetComponent<ItemInfo>();
if (itemInfo != null)
{
itemInfo.statusChanged.AddListener(OnStatusChanged);
}
}
}
}
void OnClickCloseBtn()
{
Game.uiManager.CloseUI("Panel");
}
}