- Home /
Can't pass variables between 2 scripts
hi,
I have 2 scripts, a renderItem script assigned to 10 item gameobjects(locations) out of which only 1 will spawn(render) and a globalVariables script assigned to an empty game object in the scene to select which location will be spawned.
when I run the following scripts, nothing is generated in the scene. I found out that the problem is that renderItem.js for each item cannot see any variables from the globalVariabes script. Any ideas on what I am doing wrong?
I have used the same type of setup for OnMouseDown() functions in the past and it works, why does it not work with Start() or Update()?
Thanks in advance!
renderItem.js:
var KeyObj:GameObject;// model to be rendered
var keyPosition:int;//manually set when placed in scene(1,2,3...etc)
function Start()
{
var scriptt: globalVariables = GetComponent(globalVariables);
KeyObj.renderer.enabled=false;
if((script.keyPos[keyPosition]))
KeyObj.renderer.enabled=true;
}
globalVariables.js
static var keyPos:boolean[];//key spawn poing
keyPos= new boolean[10];//10 locations to choose from
function Awake(){
//following values will be randomly assigned later on
keyPos[3]=false;
keyPos[2]=true;//spawn at location 2
keyPos[1]=false;
keyPos[0]=false; }
You can see a long explanation on http://unitygems.com/. You can find how to access variables from other scripts and an explanation on static variables in the memory management section.
Answer by aldonaletto · Nov 11, 2012 at 12:45 PM
You can access static variables directly using the script name (class name, actually) directly like this:
...
if((globalVariables.keyPos[keyPosition]))
KeyObj.renderer.enabled=true;
...
NOTE: Your original code would work only if globalVariables.js were attached to the same object as renderItems.js.
Thanks for answering! I didn't know that. I tried it but still no luck though. Also, i noticed that I get a log error:"Object reference not set to an instance of an object" for the above if statement, any clues?
Thanks again!
Do you have anything in the $$anonymous$$eyObj slot of the Inspector or does it say None(GameObject)?
You usually get errors when trying to modify prefab properties by script - do it in the instantiated object ins$$anonymous$$d. You could instantiate the $$anonymous$$eyObj first, then modify the clone like this:
var kObj: GameObject = Instantiate($$anonymous$$eyObj, ...); // get a ref to the clone
if (globalVariables.keyPos[keyPosition])
kObj.renderer.enabled=true; // set the clone renderer
...
Your answer
![](https://koobas.hobune.stream/wayback/20220613083704im_/https://answers.unity.com/themes/thub/images/avi.jpg)