- Home /
Instantiating an object as a trigger does not send the trigger event
I have a box prefab with a script attached to it that makes it so that it destroys itself after:
it hits something
or
it times out
When I instantiate this box it doesn't send a trigger event. Even if it instantiates inside of another collider. The only time it does trigger is if the player walks into it before it times out.
Script Attached to Box:
[SerializeField] float destroyTime = 1f;
float timer = 0f;
void OnTriggerEnter ( Collider other )
{
Debug.Log("Hit!");
Destroy(gameObject);
}
void Update ()
{
if (timer < destroyTime)
timer += Time.deltaTime;
else
Destroy(gameObject);
}
Script to Instantiate the box:
[SerializeField] Transform SwipeDamageArea;
[SerializeField] Transform MeleeAttackSpawn;
Quaternion[] AttackRotation;
void Start ()
{
AttackRotation = new Quaternion[6];//x, y, z
AttackRotation[0] = Quaternion.Euler(0, 0, 135);
AttackRotation[1] = Quaternion.Euler(0, 0, -135);
AttackRotation[2] = Quaternion.Euler(0, 0, 180);
AttackRotation[3] = Quaternion.Euler(0, 0, -45);
AttackRotation[4] = Quaternion.Euler(0, 0, 45);
AttackRotation[5] = Quaternion.Euler(90, 0, 0);
}
public void Swipe ( InputAction.CallbackContext context )
{
if (context.performed)
{
if(comboIncrement < 5)
Instantiate(SwipeDamageArea,MeleeAttackSpawn.position,AttackRotation[comboIncrement]);
if (comboIncrement > 5)
comboIncrement = 0;
}
}
I am incorrect for thinking that the box, when it instantiates, should see that something is already inside of it and destroy itself?
Answer by syn1221 · Feb 14 at 01:29 AM
For now (at least until I find a better way) I found a workaround where a Rigidbody will allow it to register a collider if the collider was in the spawn area before it existed. I wouldn't exactly call this answered because I don't know why this is the fix, if this is the best fix, or if this fix is the way this detection is supposed to happen given the way the engine works. I'm calling this answered for now though. Thanks to those who helped.
Answer by arrowmaster1252 · Feb 12 at 06:54 PM
Unfortunately it only detects colliders that enters it while it already exists. A workaround that could be done is to use a Physics.CheckBox
to see the stuff that is already there before you spawn the box.
And the rest of this comment is obsolete as I didn't know about the on trigger stay function. Oops.
OnTriggerStay is a dead-end as it destroys CPU performance.
Like an hour before I saw this comment I found another workaround where by attaching a Rigidbody to it I got it to register. I guess I forgot to mention that OnTriggerStay didn't work either because it doesn't get called until OnTriggerEnter gets called. I'll try Physics.CheckBox later today to see if I like it