- Home /
Accessing a Variable From Another Script
I'm simply trying to access an array of 2D textures and print "hi" if nothing is in the array slot.
In one script I have:
function Update(){
for(i = 0; i < 49; i++){
if(GetComponent(HUDAndInventory).inventoryTextures[i] == null){
print("hi");
}
}
}
In the script "HUDAndInventory" there is a total of 50 textures in the "inventoryTextures" array. I just want to iterate through each texture slot and print "hi" if nothing is assigned to it. I get the error: NullReferenceException: Object reference not set to an instance of an object. Now I understand that this error means I'm trying to reference something that isn't their, but every thing im referencing and accessing is their. So why do I get this error and how can I fix it?
Thanks!
At what point do you assign the array in the other script? Since you're running this in Update() (which means every frame from the beginning of the use of your object) you need to have assigned the array in Start(). I would recommend making a testingbutton in OnGUI() for this code ins$$anonymous$$d.
The error is probably co$$anonymous$$g from:
GetComponent(HUDAndInventory)
returning null. Then you are trying to access a variable on a null object which you can't do. Hence the NR$$anonymous$$ $$anonymous$$ake sure that you have a HUDAndInventory script attached to your game object as well.
Answer by diddykonga · Aug 21, 2011 at 05:57 AM
Try this
function Start(){
HUDAndInventory hud = GetComponent<HUDAndInventory>();
}
function Update(){
for(i = 0; i < hud.inventoryTextures.Count; i++){
if(hud.inventoryTextures[i] == null){
Debug.Log("No Texture Found");
}
}
}
For this to succesfully work you need to have this script and the HUDAndInventory script on the same GameObject. Hope this helped :)
Answer by em2 · Aug 21, 2011 at 07:48 AM
Hi MrSplosion,
If you define your array as a static var outside of your actual function you will be able to access it from other scripts / functions in your project. This will make it globally available to access.
for example:
static var yourArrayName:Array=new Array();
Hope this helps.
Cheers, Chris