Cannot cast Source from Type

Hey guys I’ve just run into an error I havn’t encountered before, I’ve been dabbling in Unity-c# for a little while so hopefully getting stuck on this isn’t too noobie.

What I’m trying to do is fill my ‘public static Tile_Levels tilesAll;’ with all children Tile_Levels that are children to the transform this script is attached to. The error is occurring on the foreach loop between Tile_Levels in transform.

void ProcessTiles(){
		
		tilesAll = new Tile_Levels[numberOfTiles];
		int TileNo = 0;

		foreach (Tile_Levels childtile in transform)
		{
				tilesAll[TileNo] = childtile;
			TileNo ++;
		}
		
		AssignMines ();
	}

Thankyou for your time, if I havn’t given enough information just ask for what you want!

It looks like you are trying to iterate (foreach) through the transform itself, which is NOT an array, list or other collection. That being said, it does CONTAIN a collection of children, an important distinction (IS vs HAS).

perhaps something like this is what you are looking for?..

...
Tile_Levels[] tileLevelChildrenArray=transform.GetComponentsInChildren< Tile_Levels >();
foreach(Tile_Levels childtile in tileLevelChildrenArray)
...

The GetComponentsInChildren will find all children that contain a component of type “Tile_Levels”. (I’m making the assumption this class is a MonoBehavior, a.k.a. “a component”.) The results will put into an array, which you CAN iterate through.

Edit: looking at your code a bit more, you may not even WANT a foreach loop after calling GetComponentsInChildren, since it looks like THAT is why you were looping… not sure though.

You already get an array from GetComponentsInChildren so you don’t need to create a new array.

void ProcessTiles()
{
    tilesAll = transform.GetComponentsInChildren<Tile_Levels>();

    for (int i = 0; i < tilesAll.Length; ++i)
    {
        tilesAll*.ID = i;*

}

AssignMines();
}