Detect collision/colliding only once

后端 未结 2 1985
生来不讨喜
生来不讨喜 2020-12-12 05:08

I have an object that moves towards another object and physically collides with it, I want that collision/colliding event to happen only once. I tried using a bool

2条回答
  •  一生所求
    2020-12-12 05:31

    If you want to run a snippet of code once, run the code directly in the callback event that you want to trigger your code.

    void OnCollisionEnter2D(Collision2D other)
    {
        DoSomeDamageTo(other.gameObject);
    }
    

    This should only trigger once upon collision.

    If you want this to only ever happen once (e.g. if the object holding the script were to hit something again), you'll need a flag to say that the damage has already been done:

    bool hasHitSomething = false;
    void OnCollisionEnter2D(Collision2D other)
    {
        if (!hasHitSomething)
        {
            DoSomeDamageTo(other.gameObject);
            hasHitSomething = true;
        }
    }
    

    I suspect given the code you've shared, that either the objects are colliding multiple times in engine (very possible if they're solid and physics-controlled), leading to OnCollisionEnter being called multiple times. OnCollisionEnter should only be called once per collision. If you are observing it being called multiple times, either you are actually observing multiple collisions, or you've found an obscure Unity bug. The former is much, much more likely.

提交回复
热议问题