- Home /
Adding scripted variables to an array
I am trying to set up way for the player to select spells during combat. I need to put them into an array so that I can I list them and scroll through them. Being a newbie to Unity Script I thought the best way to go about doing it was make a base class which would be Spell, and create my spells either by extending the spell class or just creating them from the class in a spell manager class.
So I was thinking my array would be:
var spells : Spell[];
and then add stuff like this:
fireball = new Spell("Fireball");
spells.Add(fireball);
And I get an error thats says type has to be derived from UnityEngine.Object. Type is Spell.
Are there any solutions to make my array work correctly? And if I'm going about it all wrong, how would I get an array of abilities?
Answer by Eric5h5 · Jan 27, 2013 at 04:58 AM
You cannot add to built-in arrays like that; they are a fixed size. Initialize the array to the desired size and do something like
spells[0] = fireball;
If you need the array to be a flexible size, use a generic List instead.
import System.Collections.Generic;
var spells : List< Spell >;
Lists is definitely what Im looking for, thanks. I have run into a new problem now.
I am trying to pass information from one list to another, which I managed just fine when done from a single script :
import System.Collections.Generic;
var myAbilities : List.<Ability>;
var myList : List.<Ability>;
function Start(){
fireball = new Ability(Fireball());
blizzard = new Ability(Blizzard());
myList.Add(fireball);
myList.Add(blizzard);
for(var thing in myList){
AddAbility(thing);
}
}
function Update () {
}
function AddAbility(otherThing : Ability){
myAbilities.Add(otherThing);
}
The items from the first list popped over onto the other one with no problem, but when I am trying to retrieve the information from a list in a different script it wont read it. I attached this script to the same game object and tried to get the info from one of the lists from above:
import System.Collections.Generic;
var dude : Baddie;
var spells : Blah;
var abilities : List.<Ability>;
function Start(){
spells = GetComponent(Blah);
dude = new WhiteOrb();
for(var thing in spells.myAbilities){
RoundEmUp(thing);
}
}
function RoundEmUp(someThing : Ability){
abilities.Add(someThing);
}
and the new list reading empty. I have tried it in a bunch of different ways, but I cant seem to get the information from a list in another script to transfer over. Am I missing something?
If you have two scripts with a Start function, the order in which they run is undefined, unless you use the script execution order project settings. Or use Awake in one script and Start in another.