Add Prefab by code and not by inspector

Asked

Viewed 260 times

1

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

To add a type of enemy I did the following:

  • I created an Empty Object and adding to that object a Collider 2d box with "is Trigger" enabled and a rigidbody 2d.

  • I added to the stage the first enemy 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);  
}

Note 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 runs, 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 does not suit different types of enemies.

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

1 answer

0


The problem has been solved.

Just create a folder with the name "Resources" inside the folder "Assets" and organize its resources, for example, I created the folder "Prefabs" inside the folder "Resources" and dragged there all my prefabs.

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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.