0
\$\begingroup\$

I'm writing a script (in C#) which, on mouse down, will spawn a gun and parent it to a game object. But for some reason the gun is instantiated just fine, but it doesn't parent. I have an empty game object called "Hands" and I'm trying to have the gun become a child and be moved to the position of "Hands".

To test what was going on I made two scripts, one which would parent the object upon pressing P, while the other script would just instantiate the item on mouse down. It worked, I first spawned the gun with mouse down, and then pressed P and it was parented. So my only guess is that you can't instantiate and parent in the same script all at the same time.

I have absolutely no clue what's going on, so I really appreciate any help I can get.

This is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GiveWeapon : MonoBehaviour {

  public GameObject Weapon;
  public GameObject Hands;


  void OnMouseDown ()
  {
    Instantiate(Weapon);
    Hands = GameObject.Find ("Hands");
    Weapon.transform.parent = Hands.transform;
    Weapon.transform.position = Hands.transform.position;
  }
}
\$\endgroup\$
3
\$\begingroup\$

This will fix your problem:

public class GiveWeapon : MonoBehaviour {

  public GameObject Weapon;
  public GameObject Hands;

  void OnMouseDown ()
  {
    Instantiate(Weapon, Hands.transform.position, Quaternion.identity, Hands.transform);
  }
}
\$\endgroup\$
2
\$\begingroup\$

You are trying to parent the "source" you used in the Instantiation, not the "clone" or "new object" in other words.

What you need to do is store the new object in a local variable, and use that when you do parenting.

So here is the correct form:

var newWeapon = Instantiate (Weapon) as GameObject; 
Hands = GameObject.Find ("Hands"); 
newWeapon.transform.parent = Hands.transform; 
Weapon.transform.position = Hands.transform.position;

But, there is an easier way. You can specify the parent explicitly in the arguments of Instantiate method. Check out the documentation of Instantiate method and you will see the appropriate overload for your case.

Here is a link to the documentation page of Instantiate method.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.