Global Variables with Prefabs/ Self-Naming Variables

Essentially, in my project there is a prefab, known as a “latch”. The latch can be instantiated by players, leading to an unknown amount of latches. The problem is that each latch needs to have a separate global variable, or some way to communicate with the scene’s other objects while distinguishing itself from the other prefabs.

Now, I have an idea, but I don’t know the coding to create it - or whether it’s possible. Could a new latch, upon entrance to the scene, “count” all the other latches then make a new global variable based upon how many other latches currently exist? (Example: If the latch is the 64th, then it would create a global variable “latch64”.) Can this be done? If so, how? If not, does anybody else have any ideas?

Wait I fixed it by putting it on kinematic

2 Answers

2

have a MasterScript.

static var latchList : List.<Latch> = new List.<Latch>();

Now when your new Latch is instantiated, have something like this


// create the new GameObject
newLatch = new GameObject();

// make this GameObject a "Latch"
newLatch.AddComponent(Latch);
var theLatch = newLatch.GetComponent(Latch);  

// Add the Latch to the Global Array
MasterScript.latchList.Add(newLatch);

// achieve corresponding numbering
newLatch.myNumber = MasterScript.Count;
//of course, Latch.js needs a var myNumber : int;

Hope that helps. Greetz, Ky.

Thanks! Sorry, I know a bit of code, but I’m no master. But that should definitely work!

np =) just next time... write your thanks as a comment ;)