- Home /
Question by
Vice_Versa · Jun 24, 2015 at 06:41 PM ·
nullreferenceexceptionparentchildobjectsinstatiate
how to change the Parent of an object to the current object that a script is on?
so im trying to instantiate a new object, set its parent to be the parent of the objewct that the current script is attached to, then set its rotation to the rotation of the parent object. i keep getting anull reference exception whenever i try to set the parent of the newly instantiated object. What am i doing wrong here?
Vector3 selectLocation = new Vector3 (transform.position.x, transform.position.y - 2, transform.position.z);
Vector3 orbitLocation = new Vector3 (transform.position.x + .3f, transform.position.y - 1, transform.position.z - 2f);
temp_select = Instantiate(selectButton, selectLocation, selectButton.rotation)as GameObject;
temp_orbit = Instantiate (orbitButton, orbitLocation, orbitButton.rotation)as GameObject;
temp_select.transform.parent = this.gameObject.transform;
temp_orbit.transform.parent = this.gameObject.transform;
temp_select.transform.rotation = selectButton.transform.parent.transform.rotation;
temp_orbit.transform.rotation = orbitButton.transform.parent.transform.rotation;
}
public void killButtons()
{
Destroy (temp_select);
Destroy (temp_orbit);
}
Comment
Do the "temp_select" and "temp_orbit" GameObjects get instantiated correctly? Chances are, one or both of the prefabs ("selectButton", "orbitButton") are null so no copy can be made. Use Debug.Log lines to check if the clones are instantiated correctly.
Best Answer
Answer by Flightkick · Jun 24, 2015 at 07:08 PM
You need to use SetParent() instead of setting it directly.