- Home /
Can I Put a IF In a IF?!?
Can I Put a IF in A IF? If not How do I do It??
EXAMPLE: If Cursor Is Touching Lever AND ALSO Pressing Action Button(E) Than Play Animation.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeverON : MonoBehaviour {
public GameObject Cursor;
public GameObject Lever;
void OntriggerEnter (Collider other) {
if (other.CompareTag ("Cursor")) {
Debug.Log("Cursor Has Collided")
if(Input.GetButtonDown("Action")) {
Debug.Log("Play Animation");
Lever.GetComponent<Animation> ().Play ("LeverOn");
}
}
}
}
Sure you can. Just make sure you get the curly brackets right. Do you get any erros with the code you posted? If yes, please say so.
Yeah, I use the below code and it works. I think I placed the IF's wrong.
Short answer: yes.
Longer answer: sure, but I'm not sure that's actually the solution to what you're trying to do here. It looks like you want to detect when the user has pressed the action button while the cursor is in some trigger zone.
For this, you really should have a private bool variable at the class level that you set to true in your OnTriggerEnter, and false in an OnTriggerExit. Then, in update, check for your Action button press, and make sure the bool is true at that time.
What you have will only work if the user happens to press the action key on the same frame that the cursor enters the trigger.
Answer by juicyz · Jan 26, 2017 at 12:12 AM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LeverON : MonoBehaviour {
public GameObject Cursor;
public GameObject Lever;
// As long as a gameobject stays within the trigger, this will be called over and over
void OnTriggerStay(Collider other) {
if(Input.GetButtonDown("Action")) {
if (other.CompareTag ("Cursor")) {
Debug.Log("Play Animation");
Lever.GetComponent<Animation> ().Play ("LeverOn");
}
}
}
}
Thank You So very $$anonymous$$uch!! I was about to go CRAZY! God Bless You:D
Yes you can do this, but just for future reference, it works the same to use && within the same IF statement: if (Input.GetButtonDown("Action") && other.CompareTag ("Cursor")) { //do stuff }
Answer by Sppy653 · Jan 26, 2017 at 08:36 AM
Yeah that's perfectly fine. Its just embedded if statements, more than common. I would suggest maybe using
if((other.CompareTag("Cursor")) && (Iput.GetButtonDown("Action"))
{
}
though as its just minor inefficiencies but if that seems to confusing don't worry about it.
Your answer
![](https://koobas.hobune.stream/wayback/20220612105620im_/https://answers.unity.com/themes/thub/images/avi.jpg)