- Home /
Problem with Javascript updating variables.
Hey, I'm pretty new to Unity, and I'm stuck on this error.
I have two scripts, one on a rocket launcher, and one on an ammo pickup box. When the player collides with the ammo pickup, it is destroyed, and broadcasts a message to the rocket launcher script. Here is the rocket launcher script:
#pragma strict
var projectile : Rigidbody;
var speed = 40;
public var rockets = 30;
var colour1 : Color;
var targetGuiText : GUIText;
function Start()
{
targetGuiText.text = rockets.ToString();
}
function Update()
{
if (GUIUtility.hotControl == 0)
{
if (rockets > 0)
{
if( Input.GetButtonDown( "Fire1" ) )
{
rockets --;
//Debug.Log(rockets);
targetGuiText.text = rockets.ToString();
if (rockets > 5)
{
targetGuiText.material.color = Color.red;
}
var instantiatedProjectile : Rigidbody = Instantiate(
projectile, transform.position, transform.rotation );
instantiatedProjectile.velocity =
transform.TransformDirection( Vector3( 0, 0, speed ) );
Physics.IgnoreCollision( instantiatedProjectile. collider,
transform.root.collider );
}
}
}
}
function addRockets(amount : int)
{
rockets = rockets + 10;
Debug.Log("Given Rockets, should have: " + rockets);
}
Now, this all works fine, apart from where the rockets are given. The broadcast message triggers the addRockets() function, where the amount of rockets the player has should go up. In the console, the Debug.Log prints the correct amount of rockets the player should have, but in-game, the amount doesn't change like it should. Any help will be appreciated.
Thanks!
Answer by aldonaletto · Nov 17, 2012 at 03:39 PM
If this is the whole script, the GUIText is updated only when you fire a new rocket - is this true? If so, move the GUIText related code to some place after the outermost if:
function Update()
{
if (GUIUtility.hotControl == 0)
{
if (rockets > 0)
...
}
// move the GUIText code outside the ifs:
targetGuiText.text = rockets.ToString();
if (rockets > 5)
{
targetGuiText.material.color = Color.red;
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Please tell me what is wrong with this Projectile.js file 1 Answer
FPS Tutorial from unity ??? 0 Answers
I need help with an array 1 Answer
My distance variable is not changing? 2 Answers