using UnityEngine;
using System;
public class MultiObjectController : MonoBehaviour
{
[Header("需要旋转的物体列表")]
// 在Inspector面板里把多个物体拖到这里
public YAxisRotator[] rotators;
///
/// 让所有物体转到180度,并在全部完成后打印日志
///
public void RotateAllTo180(Action callBack = null)
{
int completedCount = 0;
int totalCount = rotators.Length;
foreach (var rotator in rotators)
{
if (rotator == null) continue;
// 为每个物体调用旋转
// 使用闭包捕获 completedCount 和 totalCount 有点麻烦,因为变量会变
// 更好的方式是定义一个局部函数或使用计数器类,这里用简单的局部函数写法
if (rotator.isActiveAndEnabled)
{
rotator.RotateTo180(() =>
{
completedCount++;
Debug.Log($"{rotator.gameObject.name} 完成旋转!当前完成数: {completedCount}/{totalCount}");
// 如果所有物体都完成了(包括那些原本就不需要转的)
if (completedCount == totalCount)
{
Debug.Log("=== 所有物体旋转任务全部完成! ===");
callBack?.Invoke();
}
});
}
else
{
completedCount++;
Debug.Log($"{rotator.gameObject.name} 完成旋转!当前完成数: {completedCount}/{totalCount}");
// 如果所有物体都完成了(包括那些原本就不需要转的)
if (completedCount == totalCount)
{
Debug.Log("=== 所有物体旋转任务全部完成! ===");
callBack?.Invoke();
}
}
}
}
///
/// 让所有物体转到0度
///
public void RotateAllTo0(Action callBack = null)
{
int completedCount = 0;
int totalCount = rotators.Length;
foreach (var rotator in rotators)
{
if (rotator == null) continue;
if (rotator.isActiveAndEnabled)
{
rotator.RotateTo0(() =>
{
completedCount++;
if (completedCount == totalCount)
{
Debug.Log("=== 所有物体已归零! ===");
callBack?.Invoke();
}
});
}
else
{
completedCount++;
if (completedCount == totalCount)
{
Debug.Log("=== 所有物体已归零! ===");
callBack?.Invoke();
}
}
}
}
}