Adding id variable # to instantiate-ed object


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.

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.

You could do a few different things.

  • Set the name of the game object to be the number, using ` = 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.