- Home /
Unity object cloning and public/private variables
I've noticed that when cloning objects in Unity, the values of public variables are carried over, but private variables are not. I'd like to know the exact rules around this because I can't find it in the documentation or the forums. Might be to do with serialization of public variables?
Example, say we have a simple GameObject with the following script:
using UnityEngine;
public class TestObjScript : MonoBehaviour {
public bool HaveInited = false;
public void Init() {
if (HaveInited) {
print("Skipping Init");
return;
}
print("Init");
HaveInited = true;
}
}
And then we make an object cloner:
public class TestObjCloner : MonoBehaviour {
public TestObjScript Original;
TestObjScript origInstance;
// Use this for initialization
void Awake () {
origInstance = (TestObjScript)Instantiate(Original);
origInstance.Init();
for (int i = 0; i < 2; i++) {
TestObjScript newObj = (TestObjScript)Instantiate(origInstance);
newObj.Init();
}
}
}
Output is:
Init
Skipping Init
Skipping Init
But say we make HaveInited a private variable; then output is:
Init
Init
Init
Your answer
Follow this Question
Related Questions
Crash when using GameObject.Instantiate 2 Answers
Instantiate scripts with class relationships 1 Answer
How can I get the x position for the left(and right) of the screen? 2 Answers
How do I make a clone of a prefab appear on the correct layer? [5.2.2f1] 1 Answer
Assigning gameobject to an instantiated prefab through script? 2 Answers