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
Answer by Morozov_5f · Jan 13, 2016 at 02:29 PM
It can be done in two ways:
Use
FindObjectsOfType()
functionUse 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 :) I'd rather use second way, because it's fast and doesn't use any additional memory.
You can find more information about this function here: FindObjectsOfType()
I noticed you called it as a string, does that matter. If i'm using a called variable from another action (1,2,3,4, etc) will it still match it to that enemy?
ie, can I say if gameObject.name = 1 - is it going to get confused by strings vs numbers?
The 2nd looks like it will work a bit better for what I have in $$anonymous$$d though :) thanks
Yeah, it will matter. I have to correct myself, in second way you should assign name in that way:
gameObject.name = (++EnemyBehavior.EnemiesCount).ToString();
Otherwise, if you don't explicitly do toString conversion, compiler will be confused by trying to assign number to string. To yeah, you have to do the conversion.
Your answer
Follow this Question
Related Questions
IsGrounded not updating properly 1 Answer
How to monetize Unity game ? 0 Answers
Forge-like in game editor 0 Answers
how can i control scale speed ? 1 Answer
Building system problem 0 Answers