Hello everybody!
I have been struggling a lot with this problem: i cannot dinamically access instantiated prefab.
The following is the code i am using:
var prefab: Transform;
function Start () {
var instance = Instantiate (prefab, Vector3 (0,10,0), Quaternion.identity);
instance.transform.position.x = 10;
}
the script seems pretty straightforward: i have assigned it to the main scene camera, and i have dragged the desired prefab to the "prefab" variable in the inspector. I should be instantiating an "instance" clone of "prefab": yet i seem unable to accomplish this task, as adding the line "instance.transform.position.x=10" returns the following error:
'transform' is not a member of 'UnityEngine.Object'.
i assume i should declare the variable type of instance (like var instance : GameObject = ..., wich does not work).
Any idea? can you point me the right direction?
Instantiate returns a UnityEngine.Object, which is not the same as a GameObject, so you will have to cast the returned Object to a GameObject before you can use its transform component.
After testing this in Unity iphone I realized that it seems to work differently from the normal unity version. To get what you want you have to this:
var prefab : Transform;
function Start () {
var go : GameObject = GameObject.Instantiate(prefab);
Debug.Log(go.transform.position.x);
}
The point is that JavaScript will do the casting for you, but for this to work you will have to "type" the variable.
You declared and Instantiated instance, already as a Transform, so you wouldn't refer to its transform component. If you had declared instance as a GameObject, then you would refer to transform.
Update: Instantiatecan be used on Transforms and other derivatives from Object, and it returns whatever type you cloned.