Accessing Prefab's field before instantiation

I’m creating a game strongly based on an OOP approach, and I’ve encountered this problem:

At a given point, I have to buy an animal among many, each one with it’s own class inheriting from a superclass.
To do so, I have to check the price of the animal before instantiation, so I should access the script attached to the prefab(but considering that each script has a different name, so I can’t just do GetComponent() )

I’ve found a couple of solutions by having a list of the prices in the shop class or instantiating the gameObject, checking if the price is ok and, if not, destroying it, but both the solutions are not very OOP friendly, i suppose.

Any suggestion?

Thx! :slight_smile:

Bump

Bump, again. Sorry but I’m still looking for a solution.

How do you check the price of the object after instantiating it? Can you not just do that same check BEFORE instantiating it?

e.g.

GameObject _Prefab = Resources.Load("MyPrefab");

PriceComponent _Price = _Prefab.GetComponent<Price>();

if(_Price.Cost < 100)
{
    //Instantiate it now
}

You mentioned you “can’t just do GetComponent” - so just replace the GetComponent bit with whatever you actually do to check the price.

1 Like

Thanks for your reply. I’ve managed to find the solution I was looking for.
Basically you can call the superclass as component of the animal and call any method overriden by the subclass your prefab is binded to. The method will work as if called by the subclasses the prefab is binded to.

anyAnimalPrefab.GetComponent().Cost

will return the cost of the specific animal your pointing at, no matter if is a MouseScript animal or ZebraScript animal.

Hope it will help somebody else. :slight_smile:

1 Like

Good solution, thanks.

For those who do not understand what the OP is asking: say we have a base script class,

public abstract class BaseAnimal : MonoBehaviour {
    public int price;
}

and then specific implementations of animals[ICODE][/ICODE] that inherit from this,

public class MyAnimal : BaseAnimal {
    // whatever
}

Now we need to check the price of any animal before instantiation. To do that, we can simply get the base class component on the prefab, i.e.

int myPrice = myAnimalPrefab.GetComponent<BaseAnimal>().price;