Store instantiated object in List
I'm trying to instantiate a prefab, and saving it in a List. But I do have some troubles doing this. the spawnSnake()
method will spawn the objects, but when I look into the inspector, I see that the elements are set to 'None (Box Collider 2D)'.
I need to access the objects spawned within my code, but can't figure out how. Even though I've been searching through the forums.
What I have so far:
public Transform snakeTransform;
public List<BoxCollider2D> snake = new List<BoxCollider2D> ();
void Start () {
spawnSnake ();
}
void spawnSnake(){
for (int i=0; i<3; i++) {
snake.Add( Instantiate (snakeTransform, new Vector3(-(boardSize*tileSize/3), -3+i, 1), Quaternion.identity) as BoxCollider2D);
}
}
Answer by ARKMs · Nov 04, 2015 at 03:54 AM
You can't access the BoxCollider2D with "as" when instantiate a new GameObject, you need to obtain the component with GetComponent,, in this way:
snake.Add( (Instantiate(snakeTransform, new Vector3(-(boardSize * tileSize / 3), -3 + i, 1), Quaternion.identity) as GameObject).GetComponent<BoxCollider2D>() );
Answer by Potices · Nov 04, 2015 at 07:25 AM
Okay, I finally figured it out. The answer will be here so others can use it as a help.
The problem was the first parameter of Instansiate. It takes an object, but I casted a Transform instead. Changed the transform to GameObject as well as the List, and it works like a dream.
Your answer
Follow this Question
Related Questions
Null reference exception instatiante? 0 Answers
Instantiate working in Awake but on in Update 1 Answer
Attach MonoBehaviour in Inspector to List of MonoBehaviours on a Component 0 Answers
Getting "object reference not set" error when creating a list dictionary. 1 Answer
List.contain only one variable 1 Answer