fynmnx
fynmnx

Reputation: 611

How to swap out child of a gameobject in Unity?

I want my player to pick up a gun prefab that is a dropped item then swap the old gun for a new gun. Current structure looks like this: enter image description here

So the idea is my player picks up the prefab on the ground: enter image description here

This what I tried. My idea was to instantiate a child to the player then somehow remove the Gun child and place the new gun in the same position. The fire point is already a child of my new prefab. So I just need to swap the two. The following script would be added to the drop on the ground.

public class WeaponPickUp : MonoBehaviour
{

    public GameObject launcher;

    // Start is called before the first frame update
    void Start()
    {


    }

    // Update is called once per frame
    void Update()
    {

    }

    void  OnCollisionEnter2D(Collision2D col){
         if(col.gameObject.name =="Player"){

            GameObject go = Instantiate(launcher, new Vector3(0,0,0), Quaternion.identity) as GameObject;
            go.transform.parent = GameObject.Find("Player").transform;
            Destroy(gameObject);
        }
    }


}

Any ideas where to go from here? I'd really appreciate any kind of feedback.

Upvotes: 1

Views: 2455

Answers (2)

Pikanchion
Pikanchion

Reputation: 385

You don't need to find the Player game object because the collision already detected it, and you can get the location of the gun you are replacing to use as the position for the new gun:

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.name == "Player")
    {
        Vector3 spawnPosition = col.transform.GetChild(0).position;
        Destroy(col.transform.GetChild(0).gameObject);
        Instantiate(launcher, spawnPosition, Quaternion.identity, col.transform);
        Destroy(gameObject);
    }
}

Upvotes: 3

Asad Ali
Asad Ali

Reputation: 96

Attach script to your player. In Scene view adjust your gun position and the make the prefab that's it.

  public GameObject gunPrefab;
     void  OnCollisionEnter2D(Collision2D col){
        if(col.gameObject.name =="gun"){
           Instantiate(gunPrefab, transform); //Instantiate(prefab, parent);
           Destroy(col.gameObject);
        }
}

Upvotes: -1

Related Questions