OnTriggerStay2D when trigger is spawned on object not moving
OnTriggerStay2D
does not trigger if it's being spawned on an object which is not moving. If that object moves after the trigger has spawned it will activate the trigger.
How can I make this trigger fire on Start()
if there are any enemies in it?
In my case it's an AOE field on the ground which should damage object staying inside it:
void OnTriggerStay2D(Collider2D other)
{
float timerComparison = Time.time;
if ((timerComparison - timer) * 1000 > 250)
{
other.gameObject.GetComponent<EnemyStats>().Damage(dpsValue / 4);
timer = Time.time;
}
}
I think a coroutine always looking for objects inside this field would be more expensive and not very good for me as my scene could have quite a few if these?
Unity3D has a profiler built in. You should create an implementation in the Update() function and in a Coroutine to see which is more expensive on your CPU.
If youre not totally familiar with how the Profiler works, go here: https://docs.unity3d.com/$$anonymous$$anual/ProfilerWindow.html
That page and the pages that follow go in depth about how the profiling window works.
You're welcome my dude. Always refer to the profiler first for any general profiling questions. If its not too obvious from the profiler, then ask away! Just make sure you checked the profiler first and make note of that in your edit/question.
Answer by Gatau · Jun 26, 2016 at 03:20 PM
The solution to my problem was inside the Rigidbody2D's Sleeping Mode
, of the object which contains the above script, which had to be set to Never Sleep
. The problem was not only related to when this trigger was spawned on an already existing object, but also when objects entered and then stopped moving inside this field.
The reason for this is explained on this page under the Sleeping
section: http://docs.unity3d.com/Manual/RigidbodiesOverview.html
Don't forget to click the Correct Answer button below the Upvote/Downvote buttons to ensure this question is closed properly! :D