- Home /
changing a bool in a prefab doesn't change in it's instance.
My problem is that the a instance of a prefab seemed to perfectly inherit everything form the prefab, until i introduced a public bool. the thing is when the bool is changed in the prefab during runtime, it doesn't change in the instance, but if changed in editor it does change in the instance. The actual mechanic is: when a bullet shoots the player the bool "lose" in the camera prefab is changed to true. the lose is changed to true in the prefab, but doesn't change in the instance of the camera.
Answer by Hoeloe · Jan 19, 2014 at 03:19 PM
A prefab is only a compile-time construction. You shouldn't really mess with it at runtime without very good reason. The reason it doesn't work is that there isn't really a connection between the instances and the prefab - that's just an abstraction for the editor. Once an object is created, it's an object, not connected to the prefab, so by changing the prefab, you change only things instantiated AFTER the change.
Now, as for how to fix it, what you're looking for is a static variable. Normal variables are instance-based, that is, there's a new version of a variable for each instance. Let's try an example. Take this class definition:
public class Test
{
public int a;
public static int b;
}
Now, if we do this:
Test one = new Test();
Test two = new Test();
one.a = 4;
two.a = 5;
Test.b = 6;
We find that they each contain these values:
one:
a = 4
b = 6
two:
a = 5
b = 6
Note that the second variable is the same in both, and that we assigned it by referencing the class rather than an instance. This is because it is a static variable - it it class-based, rather than instance-based. There is only ever one copy of a static variable, and it is shared between all instances of the class. This, I think, is what you're trying to achieve, and this is a much better way to do it.
thx. i somehow forgot that static variables exits lol..
Answer by Dreamhaxor · Jan 19, 2014 at 03:18 PM
Nvm found the answer my self. i just did Cam=GameObject.FindGameObjectWithTag("MainCamera") and Cam.GetComponent<SomeScript>().lose=true to actually change the bool on the camera it self instead of the prefab. But none the less it still bugs me that instances don't inherit form Prefabs during runtime...
Worth looking at my answer - it might help explain why changing the prefab didn't work.
Your answer
Follow this Question
Related Questions
How to run script in editor 1 Answer
Changing a prefab's name (via the editor) doesn't apply the new name to the prefab's instances? 1 Answer
How can I link a GameObject instance to a script variable in a Prefab using the editor? 1 Answer
What is runtime analogy for Editor's PrefabUtility.SetPropertyModifications? 0 Answers
Saving a spheremodel into a prefab 1 Answer