- Home /
Code for picking item up isn't working.,Why isn't my pick up item code working?
I am very new to c# so sorry if its obvious, but I have it so if you walk over a helmet it will be teleported onto your head. by having a trigger on the helmet and the destination a child to the player. but nothing happens when you do that. Heres the code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Teleporting : MonoBehaviour {
public Transform teleportTarget;
public GameObject theHelmet;
public GameObject thePlayer;
void OnTriggerEnter(Collider thePlayer)
{
theHelmet.transform.position = thePlayer.transform.position;
}
},I am very new to c# so sorry if its obvious, but I have it so if you walk over a headlamp it will be teleported onto your head. by having a trigger on the helmet and the destination a child to the player. but nothing happens when you do that. Heres the code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Teleporting : MonoBehaviour {
public Transform teleportTarget;
public GameObject theHelmet;
public GameObject thePlayer;
void OnTriggerEnter(Collider thePlayer)
{
theHelmet.transform.position = thePlayer.transform.position;
}
}
Answer by eneIr · May 28, 2021 at 10:31 AM
You're making the helmet appear on that position and the position is not updating, so that helmet will end up being at the same place. Maybe you should create an empty game object that is a child of the player(drag and drop it on the player game object) and set the position of that empty game object wherever you want the helmet to be. And change your script:
void OnTriggerEnter(Collider thePlayer)
{
theHelmet.position = Vector3.zero; theHelmet.SetParent(thePlayer.transform.GetChild(0));
}
Answer by Ermiq · May 28, 2021 at 10:33 AM
What your code does is:
At the moment when the player enters the trigger area, put the helmet at the player's current position and leave it there, don't do anything else.
What you need to do is attach the helmet to the player object. It should be done by setting the player object as a parent for the helmet object. Before that you also need to reset the helmet position to zero, otherwise its current coordinates will become its local coordinates relative to the player, so the helmet will hang 100 meters to the right from the player if it has been at position 100, 0, 0
in the scene:
theHelmet.transform.position = Vector3.zero;
theHelmet.transform.SetParent(thePlayer.transform);
After this the helmet will be attached to the player as a child and therefore will follow the player.