- Home /
Properly referencing a variable from another script
Having a bad day in regards to coding - I'm having problems understanding how to properly reference variables from other scripts, here's the script I want to reference.
#pragma strict
var lightcolour : Color[];
public var selection;
var firstchange = 60;
var changerate = 60;
function Update ()
{
if(Time.time > changerate)
{
changerate = Time.time + firstchange;
var chance = Random.Range(1,10);
}
if(chance == 1)
{
selection = lightcolour [Random.Range(0, lightcolour.length)];
light.color = selection;
}
}
This script works perfectly, but I want to be able to reference the variable 'selection' in another script and use it to change the GUI.color property of a GUI texture so that the colour of the GUI texture is the same as the light.
I'm just not entirely sure how I do this, I've read the documentation but I don't understand how to reference a variable from a script.
Thanks.
Firstly we need to know how the scripts are related:
Always related
Related due to a collision
On the same object
Some other way?
One of the scripts it attached to a directional light, the other to a GUI texture. They should always share that variable so if A changes, B also changes.
Answer by whydoidoit · Sep 30, 2012 at 03:50 PM
So you need to relate the two scripts together:
Create a variable of type WhatEverTheScriptYouPostedIsCalled in the script attached to the texture.
var lightScript : WhatEverTheScriptYouPostedIsCalled;
Then use the inspector to drop the light object onto the variable called lightScript.
Then use lightScript.selection in your code on the texture.
GUI.color = lightScript.selection;
Gives me an 'Object reference not set to an instance of an object' error, I've assigned the light object in the inspector so I'm not sure what's wrong.
Doesn't sound like it took then.
Before that line do an if(!lightScript) Debug.Log("Value not set");
Ah you should define selection as
var selection : Color;
I'm guessing that this isn't set yet on the first call.
Already did that, the colour isn't changing in the inspector for the GUI texture. I added the debug line and it's not doing anything, still receiving the same error as before.
Hang on - shouldn't you be changing:
GetComponent(GUITexture).color = lightScript.selection
Your answer
Follow this Question
Related Questions
Color variable matching 2 Answers
How can I reference a float variable to a GUI label in another script? 1 Answer
How to make Unitron recognise and correctly color variables and integers etc? 1 Answer
Instance(?) problems 1 Answer
How to share a variable through multiple copys of the same script 2 Answers