- Home /
Does adding the same prefab to multiple objects duplicate the code?
Hi, I am wondering about this. Say I have a prefab containing some code that I only really want to run once, but I want more than 1 object to have access to him. So I can create a variable in the script I want, and drag the prefab onto this in the inspector. But if I do this, Does it re-compile and run the same code twice?
So again, I want a script that is used to update some info about 2 players, but I need both players to know this info, so If I drag a prefab containing the info scripts to each player, does it create a new one for each player? If so, what is a better approach? I don't think messages will work for me.
Answer by Loius · Jun 05, 2012 at 06:26 PM
Sounds like you want static variables/functions.
If you have a script Game.js:
static public var health : float;
Then any script can do this:
if Game.health < 0 then Lose();
The more properly object-oriented method would be:
static private var health : float;
static public function GetHealth() { return health; }
To answer your question, though, no - there's only one compiled version of any piece of code. Separate instances keep track of their own non-static variables; there's only one copy of a static variable, no matter how many copies of the script there are.