- Home /
how to use bool from another script in if statment?
i have a script that i want to use another scripts bool in an if statement. ive managed to get my code to have no errors but its not working how i want it to. my first script (with the bool) is:
public class ActionManager : MonoBehaviour {
public bool Switch;
public float seconds = 1;
public GameObject AttackPrefab;
// Use this for initialization
void Start () {
Switch = false;
Physics2D.IgnoreLayerCollision (9, 8, true);
}
// Update is called once per frame
void Update () {
//makes attack active on fire1
if (Input.GetButtonDown ("Fire1"))
{
AttackPrefab.SetActive(true);
}
//if active,
if (AttackPrefab.activeSelf)
{
// count down
seconds -= 2 * Time.deltaTime;
}
//if seconds are less than zero
if (seconds <= 0)
{
//set attack active to false
AttackPrefab.SetActive (false);
seconds = 1;
}
if (Input.GetButtonDown ("Fire2")) {
Switch = true;
print ("switch!");
Physics2D.IgnoreLayerCollision (9, 10, true);
Physics2D.IgnoreLayerCollision (9, 8, false);
} else if (Input.GetButtonUp ("Fire2")) {
Switch = false;
print ("unswitch!");
Physics2D.IgnoreLayerCollision (9, 10, false);
Physics2D.IgnoreLayerCollision (9, 8, true);
}
}
}
i want to use the bool Switch in this script:
sing UnityEngine;
using System.Collections;
public class PlatformBackShader : MonoBehaviour {
public GameObject player;
private ActionManager Manager;
// Use this for initialization
void Start () {
Manager = player.GetComponent<ActionManager>();
}
// Update is called once per frame
void Update () {
if (Manager.Switch == true);{
print ( "it worked!" );
}
}
}
ive been searching for so long how to do this but i cant seem to get it right :(. what i want to do is change the color of a platform when the bool Switch is true. seems simple right?
thanks guys!
dont use Switch it is a reserved word use something else ins$$anonymous$$d
Answer by Landern · Oct 12, 2014 at 03:10 PM
For starters:
if (Manager.Switch == true);{
print ( "it worked!" );
}
That is wrong, you don't put a semi colon after the if condition
if (Manager.Switch == true) {
print ( "it worked!" );
}
Answer by robertbu · Oct 12, 2014 at 03:07 PM
You have an extra ';' on line 19 of your second script. It is causing the 'if' statement to be terminated so the code in the '{}' is being executed every frame regardless of the setting of 'Switch'. Your method of accessing 'Switch' in the other script correct.
Your answer
![](https://koobas.hobune.stream/wayback/20220613164936im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Is there a way to find other's components using OnTriggerEnter? 1 Answer
GetComponent, set boolean to true but it willn't revert 3 Answers
GetComponent giving error 3 Answers