- Home /
Is it possible to store variables in arrays?
I am currently trying to figure out how to store 5 variables in a array. I have my arrays size as 4 but its not letting me put variables in. I have my games so that the user picks 5 heroes and then that script saves that heroes data/gameobject to the variable. These are 2 different scripts as well so is it possible to save data to a array that's in another script? I was thinking something like:
using UnityEngine;
using System.Collections;
public class HeroArraySaver : MonoBehaviour {
GameObject heroOne;
GameObject heroTwo;
GameObject heroThree;
GameObject heroFour;
GameObject heroFive;
// Use this for initialization void Start () {
}
// Update is called once per frame void Update () {
GameObject[] array = new GameObject[4];
array[0] = heroOne;
array[1] = heroTwo;
array[2] = heroThree;
array[3] = heroFour;
array[4] = heroFive;
} }
The reason i chose GameObject is because a GameObject will be saved to these variables.
It's certainly possible to store an array of gameobjects, but if you want to store 5 of them you should declare an array of size 5, not 4:
GameObject[] array = new GameObject[5];
"Not letting me put variables in", "Not working"... why? What error message?
What do you mean by doesn't work? Is it throwing an exception? Can you provide the entire code block that isn't working?
And make sure there are private if you want to acces the gameObject by script otherwise you will make them public but you have to fill the whole array you need to have 5 gameObjects in it.
What I mean by not letting me put the variables in I mean when I type in the code array[0] = heroOne; it says it can't find that variable, I even tried declaring it and it said the same thing. Also the reason I put 4 is because arrays start at 0 right? And yes heroOne is a GameObject, the player choses his 5 heroes and they get saved to heroOne, heroTwo, etc. Also when I get back to my computer ill edit it with my full code. Thanks
Answer by agies1 · Jan 11, 2014 at 10:12 PM
Your code is valid C# code, however the Length of the Array is invalid. While C# arrays are 0 based index, when you initialize an Array you are supplying the Array size as the parameter. When I use the below code everything is valid in a new test game.
void Update()
{
GameObject[] array = new GameObject[5];
array[0] = heroOne;
array[1] = heroTwo;
array[2] = heroThree;
array[3] = heroFour;
array[4] = heroFive;
}
One observation is that you are creating a new Array on each frame, you should be careful about this, since the garbage collector will have alot of work ahead of it.
Okay thanks i just adjusted my code to match yours and now it working, i don't know why it wasn't working before since it was valid but thanks for the help and helping me understand Arrays even better!
You had '4' ins$$anonymous$$d of '5'. Arrays are 0 based but there are still five GameObjects so you must supply the total number as if it was 1-based.