using HeurekaGames;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 分帧加载 fsLoaded
/// 示例
/// Vector2 initPos = Vector2.zero;
/// comp_fsLoaded_test.Init(5, (g,index) =>
/// {
/// g.SetActiveEx(true);
/// g.GetComponent<RectTransform>().anchoredPosition = initPos;
/// initPos += new Vector2(0, 200);
///}, (t) => { LogTool.EditorError($"{t.Count}"); },0.1f);
/// </summary>
public class FrameSegmentLoaded : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
public GameObject mPrefab;//需要加载的模板
private int loadCount = 0;//加载的个数
private int needloadCount = 0;//需要加载的数量
private Action<GameObject,int> afterPerCreate;//加载后回调
private Action<List<GameObject>> overCallBack;//加载完毕回调
List<GameObject> lists;
private bool isloadOver;//是否加载完毕
/// <summary>
/// 初始化分帧加载
/// </summary>
/// <param name="needloadAllCount">需要加载的个数</param>
/// <param name="cb">加载后回调</param>
/// <param name="loadWaitTimer">加载间隔 ,默认为帧调用</param>
public void Init(int needloadAllCount,Action<GameObject,int> cb,Action<List<GameObject>> overcb,float loadWaitTimer = -1)
{
afterPerCreate = cb;
this.loadWaitTimer = loadWaitTimer;
overCallBack = overcb;
//第二次调用时如果已经加载完毕
if (isloadOver)
{
loadCount = needloadAllCount > needloadCount? needloadCount: needloadAllCount;
isloadOver = needloadAllCount > needloadCount ? false:true;
for (int i = 0; i < loadCount; i++)
{
if (i <= (needloadAllCount - 1))
{
lists[i].SetActive(true);
afterPerCreate?.Invoke(lists[i],i);
}
else
{
lists[i].SetActive(false);
}
}
}
else
{
loadCount = 0;
lists = new List<GameObject>();
needloadCount = needloadAllCount;
isloadOver = false;
}
}
// Update is called once per frame
void Update()
{
Loaded();
}
private float loadWaitTimer = 0;
private float loadTimer = 0;
private void Loaded()
{
if (isloadOver) return;
if (needloadCount == 0) return;
loadTimer += Time.deltaTime;
if (loadTimer >= loadWaitTimer)
{
loadTimer = 0;
if (loadCount < needloadCount&& mPrefab!=null)
{
GameObject go = GameObject.Instantiate(mPrefab, transform);
go.SetActiveEx(true);
afterPerCreate?.Invoke(go, loadCount);
lists.Add(go);
loadCount++;
}
if (loadCount == needloadCount)
{
isloadOver = true;
overCallBack?.Invoke(lists);
}
}
}
}
unity分帧加载脚本
于 2024-08-06 11:41:44 首次发布