It works but there's a noticable delay between the moment when the character walks into the object (collides with it) and the moment when the above code is actually executed. I can actually walk away from the trigger before it is destroyed (and the character moves pretty slow). I want the trigger to fire immediately on collision, not 1s after. Any advice?
You haven't said what your DestroyObject function does. The Destroy function in Unity takes place at the end of the current frame, so there is no noticeable delay when using that by itself.
Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.
Destroy should happen the very frame that it is called.
It is likely that your collision is not happening when you believe that it is, which is causing your perception of a delay.
You may have considered Object.DestroyImmediate, but it is more dangerous and is subject to still happening the same frame with a slight delay much like Object.Destroy.
You probably need to provide more information. The code you have up now is similar to what I use and I never experience any lag. Since Destroy(gameObject) is executed after your 'ItemPickup...' then that could cause the delay but it looks very simple on the outside.
I agree with skovacs1 that the collision is not happening when you think it is. I would add a print text function, or print into the gui function to see when that piece of code is actually executed. That's how I trouble shoot most problems, it's extremely useful to see when things are executed or when values are changed by simply making it visual. Try this:
void OnTriggerEnter(Collider other)
{
ItemPickup.IncreaseBombCapacity(other.gameObject.GetComponent<InventoryState>());
guiText.text = "Destroy happens now";
// I commented this out otherwise the GuiText will disappear with the gameObject.
// Destroy(gameObject);
}
So now it won't destroy the object but you will know exactly when this code is executed.
It turned out that my pause/unpause code was setting `Time.fixedDeltaTime = 0` on pause, and `Time.fixedDeltaTime = 1` when unpausing. Which of course is wrong (I believe the default value is 0.02) - the delta is too long and that's where the delay came from.
I was hoping my question would ring a bell: it's a pretty obvious error to recognize if you encountered it before.
I know this post is too old but I had a problem with Destroy delay (It destroy only in the frame end) but I needed it to be destroyed just in time.
The only way I found was to disable the components that was causing my problem, and then destroy the object.
foreach (Transform t in avaliablepositionsGraphics)
{
t.GetComponent<MeshCollider>().enabled = false;
Destroy(t.gameObject);
}
avaliablepositionsGraphics.Clear();