- Home /
Question by
jay19934_unity · Nov 18, 2020 at 06:39 AM ·
gameobjectparent-childparent transform
Unable to add object to Gameobject Field
I'm attempting to transform.SetParent an instantiated prefab to my player during the game, and I'm pretty sure I have the code worked out for it, only, when I attempt to add the Player Object (located in the Hierarchy) to the Game Object field on the prefab, it will not let me. I'm unsure why this is taking place (bit of a newbie, so excuse my inexperience). Attached is the relevant bit of code, located in the object's script.
public GameObject Cube;
public void OnCollisionStay(Collision collision)
{
if (collision.gameObject.CompareTag("Player"))
{ Cube.transform.SetParent(this.transform, false); }
}
Thanks!
Comment
Answer by MurphyMurph_21 · Nov 18, 2020 at 07:59 AM
Instead of
Cube.transform.SetParent(this.transform, false);
you should use this
Cube.transform.SetParent(collision.transform, false);
Your answer
![](https://koobas.hobune.stream/wayback/20220613020023im_/https://answers.unity.com/themes/thub/images/avi.jpg)