Im trying to get certain parts form a large list into a few smaller lists, and Im running into problems. I have it set up with a base Food Class. There is a Fruit and Veggie Class that extend from the Food Class and Apples and Orange Classes that extend from Fruit and Tomato and Kale Classes that extend from the Veggie class.
I threw all of my food into a list that was type Food. Im trying to use a for loop to find all the fruit veggies from that list and put all the fruit in a fruit list and all the veggies in a veggie list. Here is my script:
import System.Collections.Generic;
var apple : Apple;
var orange : Orange;
var tomato : Tomato;
var kale : Kale;
var cart : List.<Food>;
var fruitBag : List.<Fruit>;
var vegBag : List.<Veggie>;
function Start(){
cart = new List.<Food>();
fruitBag = new List.<Fruit>();
vegBag = new List.<Veggie>();
apple = new Apple();
orange = new Orange();
tomato = new Tomato();
kale = new Kale();
cart.Add(apple);
cart.Add(orange);
cart.Add(tomato);
cart.Add(kale);
for(var f : Fruit in cart){
fruitBag.Add(f);
}
for(var v : Veggie in cart){
vegBag.Add(v);
}
}
when I run the script I get an error that says:
InvalidCastException: Cannot cast from source type to destination type.
FoodCart.Start () (at Assets/Scripts/figuring shit out/FoodCart.js:30)
When I look in the inspector at runtime the fruit is added into the fruitBag, but the vegBag stays empty. Im guessing the script stops running because of the error, but the results from the component editor reads the fruit bag perfectly, even with the extra variable from the Fruit class that wasn’t in the food class.
I tried doing it backwards and adding all the fruit into fruitBag and all the veggies into vegBag and then using a for loop on each list to add them all to the cart and it works, but I don’t understand why it doesn’t work the other way around. Im looking for a way to get the larger to sort into smaller lists because I was wanting to be able add to new lists from old lists both ways.
Any advice or nudges in the right direction would be greatly appreciated, thanks.