- Home /
Ontrigger if
Im trying to make so that when i click my mouse button i want to see if my two Boxcolliders are touching and make my bool true and if true log. The problem is if i click no matter what it keeps printing where am i going wrong?
using UnityEngine;
using System.Collections;
public class Thetrigger : MonoBehaviour {
private bool triggered = false;
public GameObject square1;
void Update(){
if (Input.GetMouseButtonDown (0)) {
if (triggered |= true){
Debug.Log ("bam");
}
}
}
void OnTriggerStay2D(Collider2D coll){
if (gameObject.tag == "squarerow"){
triggered = true;
}
else{
triggered = false;
}
}
}
Thank you
Answer by IvovdMarel · Feb 10, 2015 at 07:35 AM
Replace the OnTriggerStay method with:
void OnTriggerEnter2D(Collider2D coll){
if (gameObject.tag == "squarerow"){
triggered = true;
}
}
void OnTriggerExit2D(Collider2D coll){
if (gameObject.tag == "squarerow"){
triggered = false;
}
}
The OnTriggerStay only gets called when the trigger are colliding. Therefore, using the if-else within that method is wrong. The if-else refers to the other object having a tag of the name "squarerow", not to object colliding or not.
EDIT: Also you need to fix the bug that you use gameObject.tag instead of coll.gameObject.tag. In both methods it should be:
if (coll.gameObject.tag == "squarerow"){
triggered = false;
}
I used the method you showed me but it still wont detect if colliding
Answer by tanoshimi · Feb 11, 2015 at 06:39 AM
Your syntax is incorrect. Assuming you meant to print bam when they're not touching:
if (triggered |= true){
Should be:
if (triggered != true){
i want to print bam when they are touching, but it seems as though my if else statement isn't working, i made the bool public to see it was turning on and off but it wasnt.
The other mistake was that you check the wrong gameObject. Please see my edited answer
Your answer
![](https://koobas.hobune.stream/wayback/20220613182931im_/https://answers.unity.com/themes/thub/images/avi.jpg)