C# - SetActive Random GameObjects in Loop

Hi guys.

I’m looking for a tip how to do a script with a random activing objects.

In the my 2d game(clicker) i want to have somethink like : When you kill monster then next monster is random of 5 monster, hp = max, gold = gold + gold_per_mob and the sprite is activing.

I think that must be loop in if, but I dont know so I would be grateful when someone will help.

If you dont know what I’m asking for look in this game - Clicker Heroes. (When you kill mob next will be random)

~ I have some code :

if ( current_hp_mob < 1 ) {

gold = gold + gold_per_mob;
current_hp_mob = constant_hp_mob;
mob1_lvl_1.SetActive(false);
mob2_lvl_1.SetActive(true);
if ( current_hp_mob < 1 ) {

gold = gold + gold_per_mob;
current_hp_mob = constant_hp_mob;
mob2_lvl_1.SetActive(false);
mob3_lvl_1.SetActive(true);
}

}

But this not working. Please help me.

Simples dude: Just something like this. Firstly I suggest you make the enemies into an arrary. Let me give you an example:

public class Example : MonoBehaviour {

    public GameObject[] enemies; // You'll see in the inspector you can add as many enemies as you want, and you reference them with enemies[integer of enemy you want out of the enemies. Eg the 3rd out of 5]

    // Example just to show you how arrays work a lil
    public void SpawnFirstEnemy()
    {
        enemies[0].SetActive(true); // This will pick the first enemy in that array.
    }

    public void SpawnRandomEnemy()
    {
        int i = Random.Range(0, enemies.Length); // This creates a random number between 0 and the total number of enemies in the array (Make sure you have added enemies to the array in the inspector)
        enemies[i].SetActive(true); // Creates that random enemy
    }
  
}
2 Likes

Thanks a lot for this tip. But I have one more question.

How can I deactivate this objects?

For example: Monster have 3hp, I do 1 dmg for second, so after this 3 seconds random monster is spawing.
But how deactivate this monster which one I kill?

My code:

enemies[0].SetActive (true);

if ( current_hp_mob < 1 ) {

gold = gold + gold_per_mob;
current_hp_mob = constant_hp_mob;

int i = Random.Range(0, enemies.Length);
enemies*.SetActive(true);*
}
or I must do this in loop?

Hi Makku,

I don’t think I’ll be able to understand what you’re trying to do without seeing the entire class. Are you able to do that please? Also please use code tags when posting code on the forums: Using code tags properly - Unity Engine - Unity Discussions