x


Adding id variable # to instantiate-ed object

Hello

I'm just wondering if there is a way to give instantiated objects a unique id variable

The script I am working with, and thought should work is:

var maxObjects : int = 12;
var lastgeneratedObject  : int = 0;

function Update () 
{
if (lastgeneratedObject <= maxObjects )
{
var generatedObject = Instantiate(prefabName, transform.position, transform.rotation);
generatedObject.GetComponent(scriptAttachedToPrefab).variableInScriptAttachedToPrefab = lastgeneratedObject;
lastgeneratedObject ++;
}
}

The reason being I want the different numbered instantiated objects to do different things. At the moment all the objects are receiving variableInScriptAttachedToPrefab equal to the maxObjects var (12), instead of 1, then 2, then 3, up to 12.

more ▼

asked Apr 08 '10 at 06:13 AM

kor gravatar image

kor
100 3 4 10

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

Your logic is sound - what you have should work.

However from the symptoms, it sounds like you've made your "variableInScriptAttachedToPrefab" a static variable.

Remove "static" from its definition, and it should work as expected.

more ▼

answered Apr 08 '10 at 09:09 AM

duck gravatar image

duck ♦♦
40.9k 92 148 415

You sir are a god, gentleman and a scholar

Apr 08 '10 at 11:50 AM kor
(comments are locked)
10|3000 characters needed characters left

You could do a few different things.

  • Set the name of the game object to be the number, using gameObject.name = number; or something similar to that.
  • Use Tags.
  • Create a very small component script that simply holds the value for you. You could literally do it in one line:
public int id;

Just name that "ID.js" or something similar, and then you can get the component "ID" and check its value.

more ▼

answered Apr 08 '10 at 08:01 AM

qJake gravatar image

qJake
11.6k 43 78 161

Thanks for your quick reply =) But Ducks reply to simply remove "static" from my var did the trick -_-.

I am using the naming, but want the scripts on the objects themselves to do certian tasks depending on thier id (ie - basing the xyz positions on 150 + id*width + id*spacing (I even tried converting the names into id vars lol :P -_-)

Tags - I have been trying to avoid them as much as possible, I figured having to do the find command would be somewhat expensive compaired to just linking to the object/script directly =/

Apr 08 '10 at 11:58 AM kor
(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:

x1668
x818
x35
x17

asked: Apr 08 '10 at 06:13 AM

Seen: 2467 times

Last Updated: Apr 08 '10 at 06:13 AM