在 Unity 中暂停对撞机

Pause collider in Unity

我希望对撞机在游戏开始时暂停几秒钟。我在对象上使用这个脚本。谢谢

 public class PickUpObject : MonoBehaviour {

void OnCollisionEnter (Collision Col)
{

    if (Col.gameObject.name== "Player")
    {
        Debug.Log("collision detected");

        Destroy(gameObject);

    }
}
}

您可以使用 https://docs.unity3d.com/ScriptReference/Time-realtimeSinceStartup.html 并检查它是否大于 5 :D

使用计时器检查它。

public class PickUpObject : MonoBehaviour {
    public float timer = 10f; //seconds

    private void Update()
    {
        timer -= Time.deltaTime;
    }
    void OnCollisionEnter (Collision Col)
    {
        if (Col.gameObject.name== "Player" && timer <= 0f)
        {
            Debug.Log("collision detected");

            Destroy(gameObject);

        }
    }
}

我更喜欢的方法是设置一个 _startTime 变量与场景开始的时间,然后在需要时使用它进行检查,而不是在 Update 方法中每帧递增一个值。

private float _delay = 2f;
private float _startTime;

private void Start()
{
    _startTime = Time.time;
}   

void OnCollisionEnter (Collision col)
{
    if(Time.time - _startTime < _delay)
    {
        //Exit if the time passed is less than the _delay
        return;
    }
    //Else run check against player
    if (col.gameObject.name == "Player")
    {
        Debug.Log("collision detected");

        Destroy(gameObject);

    }
}
public class PickUpObject : MonoBehaviour {

    public float delayTime = 2.0f;
    public float currentTime = 0.0f;

    private void Update()
    {
        currentTime += Time.deltaTime;
    }
    void OnCollisionEnter (Collision Col)
    {
        if (Col.gameObject.name== "Player" && currentTime > delayTime)
        {
            delayTime += currentTime;

            Destroy(gameObject);

            delayTime -= currentTime;
            currentTime = 0.0f;

        }
    }
}