How do I assign ascending numbers to a group of the same objects

I’d like to create a numbered group of objects.

So if I had 15 of the same enemy, I’d like to number each in turn, so that one is called 1, the next is called 2, etc

I’m using it the latest version of unity 3d

It can be done in two ways:

  1. Use FindObjectsOfType() function
  2. Use static variable

First way is simple enough - in your enemy behavior (for example, let’s call it EnemyBehavior) at Start() method you simply type this code:

void Start()
{
     /*
     ... here goes your initialization
     */
     gameObject.name = FindObjectsOfType<EnemyBehavior>().Length.ToString();
}

How it works - it gets all your objects with type EnemyBehavor on scene and, gets their count and assigns it to game object’s name. Note that this method is simple, but slow, if performance is very critical.

Second way is a bit more complicated. You should put a public static variable in your EnemyBehavior class, so you can access it from every object of that class and than, on Start and on Destroy you just add this counter 1 or -1:

public static uint EnemiesCount = 0;

void Start()
{
    // Again other initialization
    gameObject.name = ++EnemyBehavior.EnemiesCount;
}

void OnDestroy()
{
    --EnemyBehavior.EnemiesCount;
    // Other destroy stuff, if you have some
}

This way is very fast and relative simple too, which to use - depends on you :slight_smile: I’d rather use second way, because it’s fast and doesn’t use any additional memory.