64 lines
2.0 KiB
C#
64 lines
2.0 KiB
C#
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class ActiveStateSynchronizer : MonoBehaviour
|
|
{
|
|
#if VR
|
|
[Header("同步配置")]
|
|
[Tooltip("拖入需要同步的目标父物体")]
|
|
public Transform targetParent;
|
|
bool isInit = false;
|
|
void Update()
|
|
{
|
|
if (targetParent == null)
|
|
{
|
|
targetParent = GameObject.Find("SceneManager/niu/PTXZ")?.transform;
|
|
}
|
|
if (targetParent != null)
|
|
{
|
|
SynchronizeActiveStates(transform, targetParent);
|
|
}
|
|
}
|
|
|
|
private void SynchronizeActiveStates(Transform source, Transform target)
|
|
{
|
|
// 获取最小子物体数量以避免越界
|
|
int minChildCount = Mathf.Min(source.childCount, target.childCount);
|
|
|
|
for (int i = 0; i < minChildCount; i++)
|
|
{
|
|
Transform sourceChild = source.GetChild(i);
|
|
Transform targetChild = target.GetChild(i);
|
|
|
|
// 同步当前层级的激活状态
|
|
if (sourceChild.gameObject.activeSelf != targetChild.gameObject.activeSelf)
|
|
{
|
|
sourceChild.gameObject.SetActive(targetChild.gameObject.activeSelf);
|
|
}
|
|
if (isInit == false)
|
|
{
|
|
Toggle toggle;
|
|
Button btn;
|
|
if (sourceChild.TryGetComponent<Toggle>(out toggle) == true)
|
|
{
|
|
toggle.onValueChanged = targetChild.GetComponent<Toggle>().onValueChanged;
|
|
}
|
|
else if (sourceChild.TryGetComponent<Button>(out btn) == true)
|
|
{
|
|
btn.onClick = targetChild.GetComponent<Button>().onClick;
|
|
}
|
|
|
|
}
|
|
// 递归处理子层级
|
|
SynchronizeActiveStates(sourceChild, targetChild);
|
|
}
|
|
|
|
// 可选:处理子物体数量不一致的情况
|
|
if (source.childCount != target.childCount)
|
|
{
|
|
Debug.LogWarning($"子物体数量不一致!源物体: {source.name}({source.childCount}) 目标物体: {target.name}({target.childCount})", this);
|
|
}
|
|
isInit = true;
|
|
}
|
|
#endif
|
|
} |