If I do this:
using UnityEngine;
using System.Collections;
public class Foo : MonoBehaviour
{
static bool isInstantiated;
int bar;
void Start ()
{
if (!isInstantiated) {
bar = 1;
print (this.bar);
Foo newFoo = (Foo)Instantiate (this);
print (newFoo.bar);
isInstantiated = true;
}
}
}
I see as output (1, 0) where I expect to see (1, 1)
I guess this happens because Instantiate does not clone values from the hierarchy, just types. Am I correct in thinking that? I can't see it written clearly in the Unity docs.
After some digging: Instantiate copies values of public fields. Make 'bar' public in my code snippet and the instantiated clone will have the value set as I expect it should be.
REMOVED first explanation
EDIT
This is my code example in JS:
Variable declarations
public var bar : int = 0;
public static var isInstantiated : boolean = false;
Start method:
if (!isInstantiated) {
bar = 1;
Debug.Log("1-" + bar);
var newFoo : GameObject = Instantiate(GameObject.Find("Foo(Clone)")) as GameObject;
Foo.isInstantiated = true;
Debug.Log("2-" + (newFoo.GetComponent(Foo) as Foo).bar);
}
The output in my case is:
"1-1"
"2-1"
As it should be. So, my first explanation and guessing was wrong. The main difference I see is that you are instantiating "this" - maybe this does not work as intended and clones the prefab instead? Can you make sure that you are cloning the actual object by either using a reference from a previous Instantiate or like I did it by looking it up via Find?