Add prefab by code rather than by inspector

1

Currently my game has only one type of enemy and I want to add 3 other enemy types.

To add an enemy type I did the following:

  • I created a empty object and adding a box collider 2d with the "is trigger" option and a 2d rigidbody to that object.

  • I added the first enemy to the stage and when that enemy collides with the object I created above, a new enemy is added. This new enemy is a prefab.

In my script I have the following:

public GameObject enemy;

void OnTriggerEnter2D (Collider2D o) {
    if (o.tag == "CreateEnemy")
        Instantiate (enemy, new Vector3 (5.65f, 0, 0), Quaternion.identity);  
}

See that there is an "enemy" variable of type GameObject, it is the variable in which I drag my prefab in the inspector.

What I want is when the trigger is run, add other types of enemies and not always the same.

The problem is that I only know how to add enemies using the way described above, which is not for different types of enemies.

How do I add multiple types of enemies? Adding a list of type GameObject (where each position has a prefab that corresponds to an enemy) and then raffling one of the elements? If yes, how do I instantiate a prefab directly in the code and not by the inspector?

    
asked by anonymous 13.08.2015 / 22:22

1 answer

0

The issue has been resolved.

Just create a folder named "Resources" inside the "Assets" folder and organize your resources, for example, I created the "Prefabs" folder inside the "Resources" folder and dragged all my prefabs there. / p>

Then in the code I made the following change:

void OnTriggerEnter2D (Collider2D o) {    
    if (o.tag == "CreateBackground")
        Instantiate(Resources.Load("Prefabs/Enemy"), new Vector3 (5.65f, 0, 0), Quaternion.identity);
}
    
13.08.2015 / 23:49