64 lines
2.0 KiB
C#
64 lines
2.0 KiB
C#
using UnityEngine;
|
|
|
|
public class EnableRigidbodyAfterDelay : MonoBehaviour
|
|
{
|
|
public GameObject[] childObjects;
|
|
public float delayInSeconds = 2.0f; // 延迟启用 Rigidbody 的时间
|
|
|
|
private Vector3[] initialPositions; // 用来存储初始位置
|
|
private Quaternion[] initialRotations; // 用来存储初始旋转
|
|
private float timer = 0.0f;
|
|
private bool hasEnabledRigidbody = false;
|
|
|
|
void Start()
|
|
{
|
|
// 存储所有子对象的初始位置和旋转
|
|
initialPositions = new Vector3[childObjects.Length];
|
|
initialRotations = new Quaternion[childObjects.Length];
|
|
for (int i = 0; i < childObjects.Length; i++)
|
|
{
|
|
initialPositions[i] = childObjects[i].transform.position;
|
|
initialRotations[i] = childObjects[i].transform.rotation;
|
|
}
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
// 更新计时器
|
|
timer += Time.deltaTime;
|
|
|
|
// 如果 Rigidbody 还没被启用且计时器超过了指定的延迟时间
|
|
if (!hasEnabledRigidbody && timer >= delayInSeconds)
|
|
{
|
|
EnableRigidbodies();
|
|
}
|
|
}
|
|
|
|
// 用于启用子对象的 Rigidbody 的方法
|
|
private void EnableRigidbodies()
|
|
{
|
|
foreach (GameObject childObject in childObjects)
|
|
{
|
|
Rigidbody childRigidbody = childObject.GetComponent<Rigidbody>();
|
|
if (childRigidbody != null)
|
|
{
|
|
childRigidbody.isKinematic = false;
|
|
childRigidbody.useGravity = true;
|
|
}
|
|
}
|
|
hasEnabledRigidbody = true;
|
|
}
|
|
|
|
// 重置位置和旋转,并重新开始计时的方法
|
|
public void ResetPositionsAndRotations()
|
|
{
|
|
for (int i = 0; i < childObjects.Length; i++)
|
|
{
|
|
childObjects[i].transform.localPosition = new Vector3(0, 0, 0); // 这里设置新的位置
|
|
}
|
|
|
|
// 重置计时器和 Rigidbody 启用状态
|
|
timer = 0.0f;
|
|
hasEnabledRigidbody = false;
|
|
}
|
|
} |