- Home /
Filling array with gameObjects
I want to place gameObjects (like buildings etc) selected from an array during runtime. There will be many gameObjects, so I want to avoid manually assigning them in the inspector.
Is there a smooth way to sort/set-up gameObjects so they can be entered into an array automatically?
Any help appreciated, cheers!
Answer by duck · Apr 14, 2010 at 04:24 PM
You must have some kind of criteria for selecting them. Typically you'd want to collect them by name, or by tag, or by whether they have a specific component (or script) attached. There are various ways to do this:
By Component (or script), for example to collect together every item in the scene which has the "PowerUp" script attached, use FindObjectsOfType. Eg:
var powerUps = FindObjectsOfType(PowerUp);
By Tag, for example to collect all items which have been assigned the "PowerUp" tag, use FindGameObjectsWithTag, like this:
var powerUps = FindGameObjectsWithTag("PowerUp");
And by name, (which is the slowest method - although still sometimes useful), for example to collect all items which include the word "PowerUp" in their name, you have to first find all gameobjects, and then scan through their names. Eg:
var objects = FindObjectsOfType(GameObject);
var powerUps = new Array();
for (var obj : GameObject in objects) {
if (obj.name.Contains("PowerUp")) {
powerUps.Add(obj);
}
}
No matter how I try this, I get "UnityException: You are not allowed to call this function when declaring a variable. $$anonymous$$ove it to the line after without a variable declaration."
Answer by KingCharizard · May 15, 2012 at 03:05 AM
var levelTriggers;
function Start() {
levelTriggers = FindObjectsOfType(ColTrig);
if (levelTriggers.length > 0){
print (levelTriggers);
}
}
That should solve your problem. the error
125*UnityException: You are not allowed to call this function when declaring a variable.*125
Tells you exactly what is wrong.
First off, sorry for the double post. Secondly, I'm trying to understand this. Are you saying that because you're defining the variable levelTriggers outside of the Function, it's global and I can't declare an array of things a global variable? Or do I have that completely wrong? From what I understand, JS assumes everything is global so putting it inside of a function can make it private, again, is this correct?