Say you have the classes : Block, Lever and Enemy.
Is there a way to hold all 3 in the same dictionary. I’d like to create a dictionary that is able to return whichever is occupying a given position. There is more than 3 classes really, I’d like something more practical than holding the gameobject as a value and then analyzing what it is.
You don’t need the booleans. You can simply use the is keyword as shown below. The output of the following code reported that the first entry is a Vehicle and a Car while the second entry is a Vehicle and a Truck.
Dictionary<int, Vehicle> vehicles;
// Use this for initialization
void Start () {
vehicles = new Dictionary<int, Vehicle>();
Car sedan = new Car();
vehicles[0] = (Vehicle)sedan;
Truck semiTrailer = new Truck();
vehicles[1] = (Vehicle)semiTrailer;
if (vehicles[0] is Vehicle)
{
Debug.Log("Entry 0 is a Vehicle!");
}
if (vehicles[0] is Car)
{
Debug.Log("Entry 0 is a Car!");
}
if (vehicles[0] is Truck)
{
Debug.Log("Entry 0 is a Truck!");
}
if (vehicles[1] is Vehicle)
{
Debug.Log("Entry 0 is a Vehicle!");
}
if (vehicles[1] is Car)
{
Debug.Log("Entry 0 is a Car!");
}
if (vehicles[1] is Truck)
{
Debug.Log("Entry 0 is a Truck!");
}
}
Yeah, but keep in mind that you can’t use this for inherited objects in this way:
{
public class Vehicle { }
public class Car : Vehicle { }
public class Program
{
public static void Main(string[] args)
{
var obj = new Car();
Console.WriteLine("Is car a vehicle? " + obj is Vehicle);
}
}
}