- Home /
Question by
Killersanta · Oct 30, 2015 at 09:01 PM ·
instantiatelistprefabs
Cannot cast from source type to destination type when trying to add Prefab instantiate to a list
I'm trying to fill up a list with prefabs so I have access to all my enemies in one list, but when I try to add it to a list only one enemy spawns and I get an error "Cannot cast from source type to destination type". I tried multiple solutions I found on the internet, but none of them seem to fix the problem but instead give me other errors.
The code giving me problems is the instantiate code.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class LevelManager : MonoBehaviour {
public GameObject _enemyPrefab;
private List<GameObject> _enemyList;
//private GameObject _enemyArray[];
private int _enemyAmount;
private int _enemyXAmount;
private int _enemyYAmount;
private const int _ENEMYSPACING = 4;
private const int _LEFTBOUND = -20;
private const int _RIGHTBOUND = 20;
//--------------------------------
//METHODS
//--------------------------------
void Start () {
//--------------------------------
//INITIALIZE VARIABLES
//--------------------------------
_enemyList = new List<GameObject>();
_enemyAmount = 0;
_enemyXAmount = 0;
_enemyYAmount = 0;
}
// Update is called once per frame
void Update () {
}
public void SetUpLevel(int level)
{
//clear the still existing enemies
// for (int i = 0; i < _enemyList.Count; i++ )
// {
// if(_enemyList[i])
// {
// Destroy(_enemyList[i], 0.0f);
// }
// }
// _enemyList.Clear();
//different parameters depending on level
switch (level)
{
case 1:
SetEnemyInfo(5, 5);
break;
case 2:
SetEnemyInfo(6, 6);
break;
}
CreateEnemies();
}
void CreateEnemies()
{
for (int y = 0; y < _enemyYAmount; y++)
{
for(int x = 0; x < _enemyXAmount; x++)
{
Vector3 pos = new Vector3(x, 0, y) * _ENEMYSPACING;(Instantiate(_enemyPrefab, pos, Quaternion.identity));
Transform newObject = (Transform)GameObject.Instantiate(_enemyPrefab, pos, Quaternion.identity);
_enemyList.Add(newObject.gameObject);
}
}
}
void SetEnemyInfo(int x, int y)
{
_enemyXAmount = x;
_enemyYAmount = y;
_enemyAmount = x * y;
}
}
I was also wondering if I want to clear the list, do I have to check every index number if there's still a prefab in there and if there is destroy it? Or will they get destroyed when I clear my list.
Comment