private void RemoveDead(LivingBeing dead) // removing an element from the scene { if (dead is Fish fish) { FishList = FishList.Where(diedFish => diedFish != dead).ToArray(); //remove from array all died Fish if (fish is Carnivore carn) // remove from general delegate the action so it's not triggered anymore { AttackCarn -= carn.Attack; } else if (fish is Herbivore herb) { AttackHerb -= herb.Attack; } ReproduceFish -= fish.Mate; AddToReport(fish.name.ToString() + " died"); } else if (dead is Alga alga) { AlgaList = AlgaList.Where(diedAlga => diedAlga != dead).ToArray(); // remove from array all died algas ReproduceAlga -= alga.Grow; // remove from general delegate the growing action AddToReport("An alga disapeared"); } dead.Dispose(); // make the object disposable for garbage collector }
private void AddToArray(LivingBeing newElement) // add new element to the right array { newElement.ReportToAqua += AddToReport; if (newElement is Fish fish) { List <Fish> newFishList = FishList.ToList(); // add fish to array newFishList.Add(fish); FishList = newFishList.ToArray(); fish.Reproduce += delegate(string name, Fish parent) // link the reproduction actionby an anonymous delegate to the fish delegate { Fish newFish = (Fish)Activator.CreateInstance(parent.GetType(), name); AddToArray(newFish); }; ReproduceFish += fish.Mate; // add the mating action to the reproduction general delegate if (fish is Carnivore carn) // add the attacking action to the attacking general delegate { AttackCarn += carn.Attack; } else if (fish is Herbivore herb) { AttackHerb += herb.Attack; } } else if (newElement is Alga alga) // Add the alga to the array { List <Alga> newAlgaList = AlgaList.ToList(); newAlgaList.Add(alga); AlgaList = newAlgaList.ToArray(); alga.Reproduce += AddAlga; // add the reproduction action to the alga delegate ReproduceAlga += alga.Grow; // add the alga's reproduction action to the general delegate } newElement.death += RemoveDead; // Link the function that removes the element when it dies to the element's delegate }