Generic type?

Hello!

I’m developing a 2D game and I’ve encountered a problem.

Example:
In my game, at a certain point I will instantiate a GameObject(animal) from prefabs. It could be an horse, a dog or any other animal, and that GameObject will have to be recognized for what it is, so an horse will have some specific differences than a dog.
The thing is, I’ve already figured out that with an abstract superclass I can create methods valid for all the subclasses so that solve a part of the problem, but I don’t know how I can make a line of code(or some lines of code) that will instantiate the requested animal making it so that it can be referenced
Ex Animal animal=Instantiate(anyAnimalPrefab).GetComponent();
making it so that that line of code will Istantiate any animal I want at will ready to receive position and its methods.

I’ve already figured out a way to do it with a lot of nested ifs and lists. My question is: there is a way to do it without a damnload of ifs?

Sorry for any typo and thank you. :slight_smile:

So, you’ve got classes (components) like this?

abstract class Animal : MonoBehaviour{}
class Dog : Animal{}

And you’ve created a prefab for a dog, i.e. game object with Dog component added?

Then you can instantiate like this

[SerializeField]
Dog dogPrefab;//Assign this via Inspector

Dog dog;

void Start()
{
    dog = Instantiate(dogPrefab) as Dog;
}

Is this what you’re asking?

1 Like

Hi mate. :slight_smile:
No. not exactly.
I know already how to instanstiate a GameObject from a prefab. The thing is:

When I want to obtain a reference to a dog, usually I do

Dog dog= Instantiate(dogPrefab).GetComponent();

My problem is that if with a line of code I want to collect a reference to an animal without knowing in advance which animal I will create, then I don’t know what to do.

Example

AnyAnimalScript anyAnimal=Instantiate(animalPrefabArray[random]).GetComponent();

How can I make it so that the game will know if it must replace AnyAnimalScript with Horse, Dog o whatever?

As I said I know that I could do that with multiple lines of code and nested ifs, I’m just asking if there is a simpler way.

Thank you :slight_smile:

If you reference the prefab the way I suggested you can do this

Animal[] prefabs = new Animal[]{dogPrefab,horsePrefab};
Animal randomPrefab = ? //todo: Get random prefab from array
Animal animal = Instantiate(randomPrefab) as Animal;

But then later on you’ll still need to do some logic if you want to call a method specific to one of the animal types.

if(animal is Dog)
{
   Dog dog = animal as Dog;
   dog.Bark();
}

If you don’t have specific methods then just call

animal.DoSomething();
1 Like

Awesome :slight_smile: Thx a lot!