I have created a script in which you create a zone and any objects inside that zone gets a force applied to them. Works like a wind tunnel you could say.
Everything is working great but I wonder if im still doing this incorrectly.
Right now I have:
void OnTriggerStay(Collider other)
{
if (other.attachedRigidbody) {
other.attachedRigidbody.AddForce(new Vector3(forceX * forceMultiplier, forceY * forceMultiplier, 0.0f));
}
}
So when an object is inside the zone they get a force applied to them.
Is this the wrong approach? I know that you should only apply forces etc during FixedUpdate(). Will OnCollision, OnTrigger etc be called in sync with FixedUpdate(). I did some test that suggest it kind of gets called that often, but sometimes more often than so, but that could also be because i have multiple collision during one call from the physics engine.
Do I need to create lists of objects inside the zone, and then add/remove items and only apply forces during FixedUpdate()? Seems like a lot of overhead.
"Note: OnTriggerStay function is on the physics timer so it wont necessary run every frame. "
I don’t know about OnTriggerEnter/Exit… the docs aren’t clear exactly.
I wouldn’t put the physics code in OnTriggerStay, I would just set some sort of flag “isTriggered=true” or whatever. Then do your physics work in your FixedUpdate. You could set this flag to false OnTriggerExit or if more than Time.fixedDeltaTime passes since it was last set (if for some reason OnTriggerExit is not firing reliably.)
Yes I agree that it would be more correct to do this during FixedUpdate. However in my case it would mean adding and removing ojects from a List or array. Using a list especially which is what I would like to do would have a performance impact, not sure if it would really matter though, but still we are dealing with the iPhone here.
But since OnTriggerStay is called during FixedUpdate I would get the same result applying forces there as in the FixedUpdate, and I wouldn’t need the lists.
EDIT: Just saw the note you mentioned, seem to only be for OnTriggerStay… hmm ok, so OnCollisionStay is called during each Update then? Good to know.