- Home /
Can't Get Public Variable in Code to Update from Inspector
Hello everyone - I suspect this is a quick question. I have attached some code below. I would like to be able to use this same countdown timer code across a bunch of different levels but only modify the "allowedTime" variable in the inspector. As of right now I can't get anything I put in the inspector to update the public variable. It always locks to 90 seconds. I have tried removing the "=90" part in the script but then the timer just defaults to 0.
Any thoughts/ suggestions how to fix would be appreciated.
// the textfield to update the time to
private var textfield:GUIText;
// time variables
public var allowedTime:int = 90;
private var currentTime = allowedTime;
function Awake()
{
// retrieve the GUIText Component and set the text
textfield = GetComponent(GUIText);
UpdateTimerText();
// start the timer ticking
Tick();
}
function Tick()
{
// while there are seconds left
while(currentTime > 0)
{
// wait for 1 second
yield WaitForSeconds(1);
// reduce the time
currentTime--;
UpdateTimerText();
}
// game over
print("Game Over");
}
function UpdateTimerText()
{
// update the textfield
textfield.text = currentTime.ToString();
}
Answer by hvilela · Oct 20, 2012 at 07:07 PM
Move your currentTime = allowedTime to the awake method.
public var allowedTime:int = 90;
private var currentTime;
function Awake()
{
currentTime = allowedTime;
...
currentTime is referenced in both the Tick and UpdateTimerText methods as well so I can't move it without having reference errors.
Not the var, the value attribution. I've edited my answer, check it's clear for you now.
Brilliant. Thanks!
I have follow-up question - if I wanted to access the currentTime variable in another script how would I do that? Should I post this as a separate question?
If it solve your problem, please accept the answer. To make it accessible by other scripts you should make it public.
Answer by dunipan · Oct 20, 2012 at 09:06 PM
That doesn't work because the Tick() function also tries to access it. Any other suggestions?
Your answer
Follow this Question
Related Questions
Cannot assign Public GameObject variable in Inspector... 2 Answers
Some Public Variables doesn't display in Inspector 2 Answers
GUIText new line through inspector 1 Answer
Inspector doesn't show the public...please, help:) 1 Answer
C# | public variables in parent class should not show up in child class 1 Answer