x


Problem naming instances with incrementally numbered counter

Hi

I have a variable count that keeps count of the objects i am creating and giving them a name based on it.

There is a small bug somewhere that makes it keep the last number it had from the last run of the script, alas it don't reset to 0;

var rate : float=0.0;
var spawn : GameObject;
var cube : GameObject;
var count : int = 0;
var position : Vector3;
var text1="Press H for instructions.";
var text2="Left mousebutton = Generate cubes";
var text = text1;

function Awake() {
    count=0;
    Debug.Log(count);
}

function Update () {
    if (Input.GetButton("Fire1") && Time.time > rate) {
        position=spawn.transform.position;
        // check to see if spawnpoint is outside the room
        if (position.z <100 && position.z > -96){
            if (position.x <100 && position.x>-100){
                ++count;
                Instantiate (cube,position,Quaternion.identity);
                rate=0.25;
                count=count+1;
                cube.name=count.ToString();
            }
        }
    }
}
more ▼

asked Mar 28 '10 at 12:02 PM

Asle gravatar image

Asle
37 8 9 12

So, it remembers count, is that it? Can you clarify what you mean by "the last run of the script"?

Mar 28 '10 at 12:21 PM KvanteTore
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

You're setting the name of the prefab rather than the name of the object you just instantiated. Changes to prefabs like this are saved with your project, therefore the next instance created of the prefab (even if it's after you stopped and replayed your app) comes out with the new name.

Also it seems as though you're incrementing your 'count' variable twice, in two different ways (using ++count and also count=count+1). You just need one of these.

You need to change your code so that you get back the reference to the instance you just created, and rename that. Something like this:

var cubeInstance = Instantiate (cube,position,Quaternion.identity) as GameObject;
count++;
cubeInstance.name = "cube "+count;

(the last line also shows how you can combine a string and the count number so your objects are named "cube 1", "cube 2" etc)

more ▼

answered Mar 28 '10 at 12:43 PM

duck gravatar image

duck ♦♦
41k 92 148 415

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1683
x825
x168
x143
x101

asked: Mar 28 '10 at 12:02 PM

Seen: 1325 times

Last Updated: Mar 28 '10 at 12:47 PM