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);
		}
	}

2 Answers

2

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>() );

@warrenblyth Because if you understand the reason why someone wants to achieve something, you can help them much more effectively than if you only know what they want to achieve...

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.