Convert Int to String
I have a lot of cubes in my scene, which all of them is named a number.
#pragma strict
var amount = 25;
var objectNumber = 0;
var object : GameObject;
function Start () {
objectNumber = Random.Range(1, amount);
object = gameObject.Find(objectNumber);
}
I want to randomly select one of the cubes by using random.range, and then select the choosen number, which one of the cubes has and put it in the object variable. The problem is, that the name of the cubes are strings, and i apparantly can't choose them with a int. Is there a way i can do this? I don't want to put each of them in a array. To much time since i will be doing it with a lot of cubes.
I assume this question is answered. If that's the case, please accept the answer to close the loop on the question.
Answer by jgodfrey · Jun 18, 2016 at 03:10 PM
There are lots of ways, including...
int i = 10;
string s;
s = i.ToString();
s = Convert.ToString(i);
s = string.Format("{0}", i);
s = "" + i;
s = string.Empty + i;
s = new StringBuilder().Append(i).ToString();
Either of the first two are probably the best / most typical. The remaining ones are just to show some variety...
As an additional note, details on numeric string formatting can be found at their $$anonymous$$SDN entry. @jgodfrey's fourth example, s = "" + i;
could be utilized in conjunction with the first, s = i.ToString();
to add further formatting and organization where necessary. For example, if all your cube objects include 3-digit numbers in their names (e.g. Cube002):
// JS
objectNumber = Random.Range(1, amount);
var objectName: String = "Cube" + objectNumber.ToString("D3");
object = gameObject.Find(objectName);
The random number is generated, then turned into a 3-digit value to append to any applicable prefix.
Additionally, bear in $$anonymous$$d that Random.Range is inclusive for the $$anonymous$$imum and exclusive for the maximum values. This means that when you define amount as 25, your random number will be between 1 and 24, never able to be 25.
Answer by rhbrr5hrfgdfgw · Jun 18, 2016 at 11:41 PM
@NinjaRubberBand Yea sure, you can do something like:
#pragma strict
var amount = 25;
var objectNumber = 0;
var object : GameObject;
function Start () {
objectNumber = Random.Range(1, amount);
object = GameObject.Find(objectNumber.ToString());
}