Your scripts are okay, your difficulty is because of scene setup moderately than coding.
To be able to detect a set off collision, OnTriggerEnter2D() has some necessities:
- Each objects will need to have one
Collider2D
Part. - Not less than one
Collider2D
Part have to be a set off (Is Set off area within the Inspector, orisTrigger
property through code). - Not less than one of many (two) objects will need to have a
RigidBody2D
Part connected to it.
The rationale you want a RigidBody2D
is, set off collisions are laptop through the Mounted Replace when the physics replace is run as nicely.
Then, you could add a RigidBody2D
to both object earlier than having the ability to detect the collision. In the event you do not want precise physics on your GameObjects, you possibly can merely tick the Is Kinematic area of the RigidBody2D
Part within the Inspector: this can forestall your object from transferring because of gravity, forces and impulses
Furthermore, don’t fret about further undesired physics behaviour: RigidBody2D
+ Collider2D
behaves like a “strong” object; whereas RigidBody2D
+ set off Collider2D
detects collisions however does not have an effect on self or others’ motion (except coded in any other case by your self).
Edit
As said within the documentation:
A Kinematic Rigidbody 2D doesn’t collide with different Kinematic Rigidbody 2Ds or with Static Rigidbody 2Ds; it solely collides with Dynamic Rigidbody 2Ds.
This implies you can’t use the present setup in your scene, as each objects are kinematic. It’s good to take away the RigidBody
Part or make it not kinematic for (no less than) one of many objects.
A unique method is mentioned in this Unity Discussion board thread. You possibly can allow further collision pairs (e.g. Kinematic-Kinematic) by configuring Mission Settings > Physics > Contacts Pair Mode to “Allow All Contacts”. It’s also really useful transferring your kinematic our bodies utilizing Rigidbody.MovePosition()
and Rigidbody.MoveRotation()
from FixedUpdate
.