- Home /
Boolean from another script reads false even if i change it to true.
Basicly here i have one script, where i store my boolean.
using UnityEngine;
using System.Collections;
public class Block : MonoBehaviour
{
public bool IsBlocking;
public float blockcooldown = 2F;
public void Awake ()
{
}
void Update ()
{
blockpress ();
blockstate ();
Debug.Log (IsBlocking);
}
public void blockpress()
{
if (Input.GetButton ("Fire2") && blockcooldown >= 2F) {
IsBlocking = true;
blockcooldown = 0F;
Renderer[] rs = GetComponentsInChildren<Renderer> ();
foreach(Renderer r in rs)
r.enabled =true;
}
else {
blockcooldown += Time.deltaTime;
}
}
public void blockstate()
{
if (blockcooldown >= 1.1F)
{
Renderer[] rs = GetComponentsInChildren<Renderer> ();
foreach(Renderer r in rs)
r.enabled = false;
IsBlocking = false;
}
}
}
and if i try to read it in another code it reads as "false", but as you can see i am also reading it's state inside this code and it successfully says "true" after i press my right mouse button.
Does other code read only the public bool IsBlocking; ? Doesn't IsBlocking change when i press my right mouse button?
Are you sure you are reading it after it has been set to TRUE?
There should be a reference to this Block script in your other script. Do you have that?
Ofcourse i have a reference to it. I have this new Block block thing in the other script and i am calling block.IsBlocking from there. No idea why it keeps on being false when it is changing in front of my eyes.
Can you include the section for your other script that is referencing isBlocking?
using UnityEngine;
using System.Collections;
public class HitBox : $$anonymous$$onoBehaviour {
private HP hp;
private Block block;
private SwordAttack sw;
void Awake()
{
block = new Block ();
sw = new SwordAttack ();
hp = new HP ();
}
void Update()
{
Debug.Log (block.IsBlocking);
}
void OnTriggerEnter(Collider other)
{
if (block.IsBlocking == true) {
Debug.Log ("Block true and cd -0.5");
sw.attackcooldown = 1F;
}
if (block.IsBlocking == false) {
Debug.Log ("Block false and hp -1 ");
hp.health--;
Debug.Log ("Health now is " + hp.health);
hp.CheckHealth ();
}
}
}
Answer by Nomabond · Sep 28, 2014 at 08:54 PM
Are you attaching the Block behavior to a gameObject? To fix this you'll need to actually get the component from the gameObject that is Updating the blockpress() method.
block = gameObject.GetComponent<Block>();
http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
It now returns the value once and then stops. (Debug.Log block.IsBlocking) And a weird error comes up.
Your answer
![](https://koobas.hobune.stream/wayback/20220613163943im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
class design preference 1 Answer
Creating a class? 2 Answers
How do I make an instance of a class global??? 1 Answer
How would I access a Class Variable from another script? 1 Answer