Invalid cast Exception

I’m a bit new to C# and unity so it might be that I’m overlooking something. But I have a InvallidCastException which I cant find the cause for.

The error message :

[21:17:47] InvallidCastException: Cannot cast from source type to destination type. Dungeon.genConnections() (at Assets/Scripts/Dungeon.cs:188)

So the problem should lie in the followin line of code

Room target = (Room) roomList[j];

So I’m guessing that unity thinks there are no Room objects within roomList, though I have no idea what else would be within roomlist. The only other times roomlist is mentioned within the file is when it’s defined as variable

private ArrayList roomList;

within the constructor

roomList = new ArrayList();

and when I’m adding rooms to the list.

Room newRoom = new Room(x1, x2 - 1,
y1, y2 - 1); roomList.Add(room);

So I have no idea where this error is comming from.

if it’s a room list then it should look like this:

using System.Collections.Generic;
public class Dungeon
{
	List<Room> roomList = new List<Room> ();
}

I don’t even know what an Array list is but I wouldn’t use it for a list if you know what type of list it is.

ArrayList != Room

hope this works and makes sense!! let me know.

Have you noticed that you create a variable named “newRoom” in this code fragment but you’re adding something called “room” to your ArrayList?

Room newRoom = new Room(x1, x2 - 1, y1, y2 - 1);
roomList.Add(room);

And that’s one of the main reasons why we usually use strongly typed variables because the compiler won’t let you put a “bowl of petunias” into a variable or List of type “rocket” (given you haven’t use the infinity improbability drive recently).

If you had used a generic List like kalen_08 said the compiler would probably complain here:

roomList.Add(room);

because “room” most likely is not a Room or derived from Room. If this is not the case you presented your code wrong or you have missed an important detail you haven’t shared with us.