How to create Prefab with property

I couldn’t figure it out by myself. I need some sort of system / object like this in C#


  weight : float = 1.5;

  points : float = 0.5;


so the thing is, each of my enemy prefab should have this type of property. So when i will spawn an enemy like

Instantiate (enemies[0], position, rotation);

I like to access enemies[0] points and weight information like



Please help me out… thanks in advance :slight_smile:

You can do it like you did, but not if you store GameObject references. You should attach an EnemyScript to each of the prefabs and change the reference type to this script. If each enemy has already a specialized script attached, you might want to create an EnemyBaseClass from which all other enemy scripts are derived from:

public class EnemyBaseClass : MonoBehaviour
    public float weight;
    public float points;

// For example a script for the Asteroid enemy:

public class Asteroid : EnemyBaseClass 
    // Asteroid specific stuff
    public float size;

Now you can setup your script above like this:

// [...]
public EnemyTypes CurrentEnemyType = EnemyTypes.Asteroid;
private Dictionary<EnemyTypes, EnemyBaseClass> Enemies = null;

public EnemyBaseClass AsteroidEnemy;

void Start() {
    GameStartTimer = Time.time;
    Enemies = new Dictionary<EnemyTypes, EnemyBaseClass>(3);
    Enemies.Add(EnemyTypes.Asteroid, AsteroidEnemy);
    Enemies.Add(EnemyTypes.MiniCraft, MiniCraftEnemy);
    Enemies.Add(EnemyTypes.Banzai, BanzaiEnemy);

Another thing is that Instantiate will create an instance of the given prefab, so it makes no sense to change the prefab itself. Instantiate will return the newly created object. Instantiate will return the same type that you provide. So we give an EnemyBaseClass component so it will return that component of the cloned gameobject. However it need to be casted since Instantiate can clone any kind of Unity objects.

EnemyBaseClass clone = (EnemyBaseClass)Instantiate(Enemies[CurrentEnemyType], Position, Quaternion.identity);

clone.weight = 25.0f;

Keep in mind that the actual script that is attached to the enemy can be any derived type of EnemyBaseClass. But since our reference is of type EnemyBaseClass we can only access the EnemyBaseClass stuff which all enemy types share.

That means for example you attach an Asteroid-script to your asterois prefab and drag it onto the AsteroidEnemy variable so it will be added to the dictionary. Since the Asteroid script is also an EnemyBaseClass you can so this. From your instantiate scripts point of view it only have to work with the general EnemyBaseClass, but the actual instance will have an AsteroidEnemy script.

That’s the basic idea of inheritance :wink:

Use an Accessor:

Or attach a script to your prefab.