- Home /
I cannot collide with a dynamically made BoxCollider2D
Hi,
I am generating a new GameObject and giving it a box collider with the code below:
rightGO.name = "rightSide";
rightGO.layer = LayerMask.NameToLayer("Ignore Raycast");
rightGO.transform.parent = gameObject.transform;
rightGO.transform.localPosition = new Vector2 (0, 0);
var rightCollider = rightGO.AddComponent <BoxCollider2D>();
SpriteRenderer sprite = gameObject.GetComponent<SpriteRenderer> ();
float width = sprite.bounds.size.x;
float height = sprite.bounds.size.y;
rightCollider.size = new Vector2 (1.0f, gameObject.GetComponent<SpriteRenderer> ().bounds.size.y);
rightCollider.offset = new Vector2 (width/2, 0);
This code generates a gameobject and makes a properly scalled BoxCollider2D as a trigger. Problem is, it is not colliding with another BoxCollider2D. I have in the code in another gameobject, the following:
void OnTriggerEnter2D(Collider2D col) {
Debug.Log (col.gameObject.name);
}
But I am never debugging the gameObject's name of "rightSide." It will properly print out other 2D triggers, with similar properties for some reason.
Any idea on how to fix this?
Why are you putting your new game object under Ignore Raycast layer?
$$anonymous$$ake sure collision matrix in Physics2D settings are enabled for this layer then.
Answer by Veftaxop · May 03, 2018 at 03:20 PM
From the code you are posting, I see you never set the new collider's trigger property to true. For the OnTriggerEnter2D function to properly work you need to set the trigger property to true. A fairly unrelated advice: It is better to instead of generating a GO on runtime, you should create it in the Editor, cache it in a variable in your script and deactivate and activate at will on runtime. This way you it will be easier to make sure if your GO behaves properly and it is much more optimised.
Your answer
![](https://koobas.hobune.stream/wayback/20220612161639im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D box colliders not touching but are colliding, how to fix? 0 Answers
Multiple Cars not working 1 Answer
I don't think I get collision box, can someone help? 0 Answers
Distribute terrain in zones 3 Answers
How to call OnTriggerEnter once 5 Answers