- Home /
GetComponent - problem with var from another script
//Checking player wood
var getPlayerWood : GetWoodScript;
//Buildings
var CubeBuild : int = 10;
//var move : float = 5;
function Update ()
{
if (Input.GetKeyDown(KeyCode.B))
{
getPlayerWood = gameObject.FindWithTag("Player").GetComponent(GetWoodScript);
if(getPlayerWood.playerWood == CubeBuild)
{
if(objectInHands == false)
{
build = Instantiate(build, transform.position + transform.forward * 4.0 , transform.rotation);
build.rigidbody.isKinematic = true;
build.transform.parent = Camera.main.transform;
objectInHands = true;
//getPlayerWood.playerWood -= CubeBuild;
}
else {
print("You have Cube in your hands");
}
}
else if(getPlayerWood.playerWood != CubeBuild)
{
print("You can't create it now !");
}
}
}
"You can't create it now !" all the time ;/ I dont know why, code is good because if i add this
if(Input.GetKeyDown(KeyCode.R))
{
getPlayerWood = gameObject.FindWithTag("Player").GetComponent(GetWoodScript);
print("You have " + getPlayerWood.playerWood + " wood");
}
it works ! ;/ it looks like it haven't read var from another script ;/
Your logic for getting the value from the other component looks fine, but other things here puzzle me. Right after line 30, add:
Debug.Log(getPlayerWood.playerWood);
See what value you are getting. Any change that 'playerWood' is a float? If so the '==' comparison might be failing.
var playerWood : int = 0;
And this
Debug.Log(getPlayerWood.playerWood);
return good value, so now i totally dont know where is problem o.O
Two things. First CubeBuild is a public variable, so the value it will have is the one in the inspector, not necessarily the one you assign in code. Second, in the code above you assign 10 to CubeBuild. 10 is not equal to 0.
Gnometech - Thanks ;D Thats it ! what a mistake ;( robertbu thx u2 ;)
Ok, just for reference I converted it to an answer. And no worries, we all made beginner's mistakes. And still do. :-)
Answer by Gnometech · Feb 12, 2014 at 08:54 PM
You are aware that your script ONLY lets you build a cube if you have exactly the amount of wood required (in your case 10). So if you have 11, 12 or more it won't, because you ask if the number of wood is equal to the amount.
This is just a guess, but maybe changing the statement to
if(getPlayerWood.playerWood >= CubeBuild)
will already do the trick. Also remove the "if" from the else part, it is useless.