- Home /
Issues with trying to change a variable in another script
This script has given me all sorts of problems, and here is the new one;
I'm trying to change a variable, and call a function from a script attached to an assigned GameObject variable.
Here's the script trying that's trying to call the change;
#pragma strict
var resourceValue: int = 25;
var Countdown: int = 5;
var visible: float = 0.50;
var invisible: float = 0.50;
var blinkFor: float = 5.0;
var startState: boolean = true;
var explosion: GameObject;
var mainGUI: GameObject;
function Start ()
{
animation.Play ();
transform.position.z = -5;
renderer.enabled = startState;
yield WaitForSeconds(Countdown);
var whenAreWeDone = Time.time + blinkFor;
while (Time.time < whenAreWeDone)
{
if ( startState )
{
renderer.enabled = false;
yield WaitForSeconds(invisible);
renderer.enabled = true;
yield WaitForSeconds(visible);
}
else
{
renderer.enabled = true;
yield WaitForSeconds(visible);
renderer.enabled = false;
yield WaitForSeconds(invisible);
}
}
renderer.enabled = true;
Destroy ( gameObject );
}
function Update ()
{
var hit :RaycastHit;
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if ( Physics.Raycast ( ray, hit, 30 ))
{
if ( hit.collider.gameObject.tag == "resource" && Input.GetMouseButtonDown (0))
{
AddValue ();
Instantiate ( explosion, hit.collider.gameObject.transform.position, Quaternion.identity );
Destroy (hit.collider.gameObject);
}
}
}
function AddValue ()
{
var test = mainGUI.GetComponent(LevelMaster).resourceCount;
mainGUI.GetComponent(LevelMaster).resourceCount += resourceValue;
//mainGUI.GetComponent(LevelMaster).UpdateHUD ();
print ( test );
}
And here's the script attached GameObject assigned to mainGUI;
#pragma strict
static var playerDamage: float = 0; //records the damage the player has taken
var waveActive: boolean = true; //toggles for controlling the wave
var spawnEnemies: boolean = true; //
var bigSpawn: boolean = false;
var firstWaveActive: boolean = true;
var secondWaveActive: boolean = false;
var healthCount: int = 10; //players health count
var resourceCount: int = 50;
var waveText: UILabel; //ui label
var resourceText: UILabel;
var waveLevel: int = 0; //current wave we are on
var waveLength: float = 0; //how long does the wave last before it stops
var intermissionTime: float = 15.0; //how long to wait inbetween waves
var enemyPrefabs: GameObject[]; //array that contains all the enemy types
var enemyPrefabs02: GameObject[];
var alienSpawnPoints: Transform[]; //contains the spawn points
var respawnMinBase: float = 3.0; //used to ramp up the amount of spawns
var respawnMaxBase: float = 10.0; //
private var respawnMin: float = 3.0; //
private var respawnMax: float = 10.0; //
private var waveEndTime: float = 0.0;
var difficulty: int = 0;
var seconds: int = 0;
var minutes: int = 0;
function Start ()
{
}
function Update ()
{
Clock ();
if (waveActive)
{
if ( Time.time >= waveEndTime )
{
spawnEnemies = false;
FinishWave ();
print ( "shutting off wave");
}
}
if ( minutes >= 1 && firstWaveActive )
{
firstWaveActive = false;
secondWaveActive = true;
print ( "swapping over to second wave level");
waveLength = 5;
}
if ( waveLevel == 09 && secondWaveActive )
{
secondWaveActive = false;
bigSpawn = true;
print ( "swapping over to big spawn");
waveLength = 40;
FinishWave ();
}
if ( minutes >= 4 )
{
difficulty = minutes - 2;
}
}
function FinishWave ()
{
waveActive = false;
spawnEnemies = false;
var i: int;
if ( firstWaveActive )
{
i = Random.Range (20, 30);
print ("under 1 minute, waiting for "+i);
yield WaitForSeconds (i); //waits for the the intermission time to pass
SetNextWave (); //sets the next wave command
StartNewWave ();
}
if ( secondWaveActive )
{
i = Random.Range (12, 18);
print ("over 1 minute, waiting for "+i);
yield WaitForSeconds (i); //waits for the the intermission time to pass
SetNextWave (); //sets the next wave command
StartNewWave ();
}
if ( bigSpawn )
{
print ("HERE THEY COME!!!");
yield WaitForSeconds (10);
SetNextWave ();
StartNewWave ();
}
}
function SetNextWave () //prepares the values for the next wave (how many enemies will be spawn)
{
waveLevel ++; //ups the wave level
}
function StartNewWave ()
{
UpdateHUD (); //updates the gui
NewSpawnEnemy (); //spawns new enemy
waveActive = true; //sets the toggle to spawn enemies
spawnEnemies = true;
waveEndTime = Time.time + waveLength;
}
function UpdateHUD ()
{
waveText.text = "Wave: " +waveLevel; //updates the current waveLevel to the wave GUI
resourceText.text = "Resources: " +resourceCount; //updates the current healthLevel to the health GUI
}
function NewSpawnEnemy ()
{
if ( minutes <= 1 && firstWaveActive && !bigSpawn )
{
FirstLevelSpawn ();
print ("first level spawn happening");
}
if ( minutes >= 1 && !bigSpawn && secondWaveActive && !firstWaveActive )
{
SecondLevelSpawn ();
print ("second spawn happening");
}
if ( bigSpawn && !secondWaveActive )
{
BigSpawn ();
print ("big spawn happening");
}
}
function FirstLevelSpawn ()
{
var i = difficulty;
for (; i >= 0; i--)
{
var enemyChoice = Random.Range (0, enemyPrefabs.Length);
var spawnChoice : int;
spawnChoice = Random.Range (0, alienSpawnPoints.Length);
Instantiate (enemyPrefabs[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
print ( "1 enemy spawned");
}
}
function SecondLevelSpawn ()
{
var i = difficulty;
for (; i >= 0; i--)
{
var enemyChoice = Random.Range (0, enemyPrefabs02.Length);
var spawnChoice : int;
if ( enemyChoice == 1 )
{
var a = 1;
for (; a >= 0; a--)
{
spawnChoice = Random.Range (0, alienSpawnPoints.Length);
Instantiate (enemyPrefabs02[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
}
}
if ( enemyChoice == 0 )
{
spawnChoice = Random.Range (0, alienSpawnPoints.Length);
Instantiate (enemyPrefabs02[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
}
}
print ( "second level spawn finished" );
}
function BigSpawn ()
{
print ("Big Spawn!");
var i = 3;
for (; i >= 0; i--)
{
var enemyChoice = Random.Range (0, enemyPrefabs02.Length);
var spawnChoice : int;
if ( enemyChoice == 1 )
{
var a = 1;
for (; a >= 0; a--)
{
spawnChoice = Random.Range (0, alienSpawnPoints.Length);
Instantiate (enemyPrefabs02[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
}
}
if ( enemyChoice == 0 )
{
spawnChoice = Random.Range (0, alienSpawnPoints.Length);
Instantiate (enemyPrefabs02[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
}
print ( "big spawn loop "+i);
}
bigSpawn = false;
secondWaveActive = true;
waveLength = 5;
print ("big spawn finished");
}
function Clock ()
{
seconds = Time.time % 60;
minutes = Time.time / 60;
}
So while I look at the value of "resource Count" while the game is going, it doesn't go up at all. It stays at 50 in the inspector. What I find weird is, if I call that print command "test" to tell me what the current value of "recource Count is", I get something else. And while most of the time, it's adding a straight "25" to the value, I'm finding that sometimes it's adding a ton more. 75-100 in some cases.
As you can see, I've also commented out trying to call the function from the script "LevelMaster", It was giving me a NullReferenceException: Object reference not set to an instance of an object LevelMaster.UpdateHUD () (at Assets/Scripts/LevelMaster.js:124) Which drives me nuts, because that script is clearly attached to the GameObject assigned to mainGUI in the inspector.
Very confused here. :(
Answer by clunk47 · Sep 05, 2013 at 04:12 PM
I'll just skip over all this code and give an example in JS on how to access a variable from another script using GetComponent. Lets say you have a script with a GameObject variable assigned, and that GameObject has another script attached called "ScriptToAccess". In this "ScriptToAccess" class, you'd have a variable called "score". Let's say as a test, you want to hit 'E' to add score on each keypress:
#pragma strict
var go : GameObject;
function Update()
{
if(Input.GetKeyDown(KeyCode.E))
{
if(go.GetComponent(ScriptToAccess))
{
go.GetComponent(ScriptToAccess).score += 100;
}
}
}
He's trying to call a function so
go.GetComponent(ScriptToAccess).callingFunction();
The problem with the variable not being reset sounds like you need to CLONE your prefab.
//Assign your prefab to this in inspector.
var lm : GameObject;
//Use instantiation in any function, this is just an example method.
function ClonePrefab()
{
//Clone lm GameObject and bring in a new instance to your scene, so your prefab will not be affected.
var lmClone = Instantiate(lm, transform.position, Quaternion.identity);
}
I noticed the underscore too, but it doesn't make a difference, underscores are fine for object names.
The _ just keeps the prefab at the top of the Hierarchy, and easy to find. It was just a trick I saw once in a tutorial.
static is just kind of sloppy if you're using it on GameObjects as far as I know, you have to reset things manually in some conditions. Usually the only reason I use static is for a script not attached to anything in the game, and use scripts attached to gameObjects to access the static class. Another reason to use static would be for Editor scripts in Unity. If you choose to use static, there can be only ONE instance of the variable or class.
Your answer
Follow this Question
Related Questions
Accessing a variable that has a unique class 2 Answers
How could you access a script of varying name? 5 Answers
C# line into Javascript help 1 Answer
Access variable from multiple scripts 2 Answers