Lists of Generic Scriptable objects

Hi guys,

So I am now using SO a lot in my project and I now have a problem where I need to create lists of these scriptable objects.
So this is easy I can make a SO (MyScriptableObject) and in another script make a List.

But say I have CatSO, DogSO both have color and age. So I do not want to create two Lists, I want to be able to have one List and be able to drop in cats and dogs.
And be able to access their names and age?

I tried to create an empty Animal SO and derive from it when creating CatSO and DogSO. All good.
Now I have a different script I create List and I can drop in Cats and Dogs , all good.
But for some reason, I can’t access cats and dogs public properties.

List<Animal> animals = new List<Animal>();
private string name;

name = animals[0].name;

Thank you

Or better is to have an Animal list as a separate SO with cats and dogs :slight_smile:

Remove the Color and Age properties from the Cat and Dog. Add those properties to the Animal. Then, you can access those properties from a List and Cat and Dog will inherit them from the base Animal class:

public class Animal
{
    public Color Color { get; set; }
    public int Age { get; set; }
}

public class Dog : Animal
{

}

public class Cat : Animal
{
 
}

Dog dog = new Dog();
Cat cat = new Cat();

List<Animal> animals = new List<Animal>();
animals.Add(dog);
animals.Add(cat);

foreach(Animal animal in animals) {
    Debug.Log(animal.Age);
}

Thank you @wbm1113
Yep, I see. I started with this. This is clear. But I am working with Scriptable Objects.
If I will keep name and age in animal, it will mean I will not be able to set these in Cat and Dog scriptable assets!?

It seems I have to use an abstract class with name and age in it …?

Ok Cool it works with Abstract Class!

It doesn’t need to be abstract, abstract just ensures you don’t create instances of Animal.

serialized fields that you inherit from a base class will be settable in your editor.

You can do this:

public class Animal : ScriptableObject
{
    [SerializeField]
    public Color color;
    [SerializeField]
    public int Age;
}

public class Dog : Animal {}

public class Cat : Animal {}

Now personally I probably would make Animal abstract… but that has nothing to do with if the fields are serialized.

Thank you @lordofduct it make sense

Ok, so I have to declare some field within base class?
Otherwise, if I am trying to access a list item I am getting an error :

 'DataBase' does not contain a definition for 'StreetColor' and no accessible extension method 'StreetColor' accepting a first argument of type 'DataBase' could be found (are you missing a using directive or an assembly reference?)

Never mind got it to work :slight_smile: