- Home /
 
Unity 3D: How to pick up object and attached it to player on TriggerEnter?
I want my player to carry the axe with him when he touched it (see photo below 1.png). I know it has to do with the transform the parent thing but I can't seem to understand tutorials about it. I only figured out how to destroy the axe when I approach it and create another prefab of the axe near my player, but the axe just stays where it is and doesn't follow me (hence what I said earlier on how I can't understand the transform parent). I know what parent and child are (I actually created my player with the camera that follows him with his movement). Here's what I coded so far:
 public Transform Spawnpoint;
 public GameObject Prefab;
 void OnTriggerEnter(Collider collider)
 {
     if (collider.gameObject.tag == "Player")
     {
         Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation);
         Destroy(gameObject);
     }
 }
 
               }
Answer by sujitmarcus · Apr 11, 2020 at 02:11 PM
You Could do this in various way.. 1. Your player could have array of weapons from which he can only have one active at a time. and OnTriggerEnter could trigger the function.
Attach this on player Object.
For example
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Player_WeaponManager : MonoBehaviour
 {
 
     public GameObject[] Weapons;
     public GameObject _currentWeapon;
 
 
     public Transform Spawnpoint;
     public GameObject Prefab;
     // Start is called before the first frame update
     void Start()
     {
         //Assigning default Weapon
         // Weapons[0] could be some other wheapon
         SwitchWeapom(0);
     }
 
     // Update is called once per frame
     void Update()
     {
         
     }
 
 
     public  void SwitchWeapom(int index)
     {
         _currentWeapon = Weapons[index];
         //instantiate Current Weapon
         GameObject obj =  Instantiate(_currentWeapon, Spawnpoint.position, Spawnpoint.rotation);
         obj.transform.parent = this.transform;
 
     }
 
  
     void OnTriggerEnter(Collider collider)
     {
         if (collider.gameObject.tag == "AxePickup")
         {
             Destroy(collider.gameObject);
             // On weapons array 2 could be the axe
             SwitchWeapom(2);
         }
     }
 }
 
              Your answer
 
             Follow this Question
Related Questions
How to transform parent object from child? 1 Answer
Fixing pivot points with second gameObject workaround 1 Answer
Kinematic Child Object Jumping Above Player 1 Answer
moving child objects in hierarchy and keep stacks/sorting? Help needed 0 Answers
Howto set main.camera as a parent when main.camera itself is a child of a prefab 1 Answer