Prefab instantiation get position issue
Hi,
I am going crazy about this and perhaps it is just that I am tired and doing something really stupid, but I am currently seeing a very weird bug when instantiating a prefab. So I create a prefab which contains a rigid body. Then I simply instantiate it programmatically and try to read the rigidbody position in the update loop. I see that the position never changes!!!! However, if I manually drag the same prefab into a running scene and assign it to a game object variable in the same script it reads the position just fine as I move it around. There seems to be something about programmatically instantiating it... Here is the simple script I run to test this. The prefab only contains a cube with a rigid body.
What I am doing wrong? I am going crazy about this...
Any help is very much appreciated! Thanks!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InstantiationTester : MonoBehaviour
{
public GameObject prefab;
public GameObject obj;
// Start is called before the first frame update
void Start()
{
obj = Instantiate(prefab, new Vector3(0,10,0), Quaternion.identity);
}
// Update is called once per frame
void Update()
{
Debug.Log(prefab.GetComponentInChildren<Rigidbody>().transform.position + " " + obj.transform.position);
}
}
Answer by reyes73a · Apr 13, 2020 at 02:02 AM
Ok so for those of you with the same issue. I just figured it out i think. Basically you should be assigning the instantiation result to a game object and from there on you use that game object to access scripts and other objects within the instantiated prefab. If you do this it works properly. If instead you try to reference the prefab object directly (prefab var in my example) you will have all sorts of issues:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InstantiationTester : MonoBehaviour
{
public GameObject prefab;
public GameObject obj;
// Start is called before the first frame update
void Start()
{
obj = Instantiate(prefab, new Vector3(0,10,0), Quaternion.identity);
}
// Update is called once per frame
void Update()
{
Debug.Log(obj.transform.position);
}
}