- Home /
My trigger dont work (2D platformer)
I'm beginner to unity. I want to make 2D platformer and i created first moving enemy. I wrote script which I think is fine but I wanted to make enemy go back and forth.
[SerializeField] private Transform LeftCheck;
[SerializeField] private Transform RightCheck;
So I've created 2 empty object and gave it box colliders and put in into the object and I wanted my enemy to flip every time he touches one of them so I wrote something like this. void OnTriggerEnter2D(Collider2D coll) { if (coll.gameObject == RightCheck || coll.gameObject == LeftCheck) { Flip(); } }
Can you tell what I'm doing wrong? Both box colliders have isTrigger checked. I know the problem is with if condition cause eariler I did this using coll.gameObject.tag and it was working but I thought this way would be much more elegant. Sorry for my English too.
Answer by NSMcInroy · Feb 17, 2021 at 08:07 PM
Currently your code compares coll.gameObject (which is a type of GameObject) with RightCheck and LeftCheck (which are both of type Transform). They will never be equal.
Solution 1: - Grab the transform from the collider game object like this coll.gameObject.transform
void OnTriggerEnter2D(Collider2D coll) { if (coll.gameObject.transform == RightCheck || coll.gameObject.transform == LeftCheck) { Flip(); } }
Solution 2: - Grab the gameObject from the two transforms like so RightCheck/LeftCheck.gameObject
void OnTriggerEnter2D(Collider2D coll) { if (coll.gameObject == RightCheck.gameObject || coll.gameObject == LeftCheck.gameObject) { Flip(); } }
Solution 3: - Make RightCheck and LeftCheck GameObject types and skip the conversion entirely
[SerializeField] private GameObject LeftCheck;
[SerializeField] private GameObject RightCheck;
Solution 4: - As someone else has mentioned you may also want to check against tag as it tends to be more performant but seeing how this code doesn't seem to be called all that often it might be unnecessary. - In this scenario you do not need to keep a reference to the left and right checks and could just tag them accordingly.
void OnTriggerEnter2D(Collider2D coll) { if (coll.gameObject.CompareTag("FlipCheck")) { Flip(); } }
Answer by GDGames0302 · Feb 17, 2021 at 06:41 PM
Use the variant you did earlier, coll.gameobject.tag . Never find or access objects by name, because it is slowing performance, always find objects by tag. Hope it helps.