- Home /
Transform[] syntax error
Type UnityEngine.Transform[]' does not contain a definition for
Add' and no extension method Add' of type
UnityEngine.Transform[]' could be found (are you missing a using directive or an assembly reference?)
I'm getting error when I try to add spawn to array
using UnityEngine;
using System.Collections;
public class SpawnController : MonoBehaviour
{
private Transform[] spawnsList;
private int numberOfSpawns;
public GameObject prefab;
public int noPrefabsToSpawn;
void Awake ()
{
numberOfSpawns = transform.childCount;
spawnsList = new Transform[numberOfSpawns];
GameObject container = GameObject.Find("SpawnContainer");
foreach (Transform spawn in container.transform)
{
// add the spawn to the array
spawnsList.Add(spawn);
}
}
}
If one of the two answers below answered your question, please click on the checkmark on the left side of that answer to close it out. Thanks.
Answer by rutter · Feb 04, 2014 at 01:35 AM
As the compiler says: C# arrays do not have a function named Add
.
If you want to use a static array:
spawnsList = new Transform[numberOfSpawns];
int counter = 0;
foreach (Transform spawn in container.transform) {
spawnsList[i++] = spawn;
}
If you want a dynamically sized collection, you might instead use a List
:
spawnsList = new List<Transform>();
foreach (Transform spawn in container.transform) {
spawnsList.Add(spawn);
}
See the Unity wiki: Which Kind Of Array Or Collection Should I Use?
In particular, their section on the List<T> class.
Answer by Roland1234 · Feb 04, 2014 at 01:42 AM
Arrays have no Add method, you'll have to either manually allocate the number of elements when instantiating (like you do on line 26) and set the values by index (spawnsList[x] = value; making sure the index x doesn't go out of bounds), or simply use a List which does have an Add method defined and will dynamically grow in size (not requiring you to set it's capacity beforehand). I'd recommend the latter in your case, although I'm not entirely clear on what you are trying to accomplish.
Sure thing, although I think rutter got to it first and gave a more complete answer ;)
Your answer
Follow this Question
Related Questions
Keep adding targets to a list 2 Answers
Remove and Add to List By Name aad 1 Answer
A node in a childnode? 1 Answer
Find Target From List 1 Answer
List.Sort with IComparer 2 Answers