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);
}
}
}
You Could do this in various way…
- 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);
}
}
}