# How to parent object to empty when looked at

I am making a fps in unity. I have an empty parented to the camera for the gun, and I want to be able to pick up and drop guns found in the scene. Does anyone have a simple c # script that would allow the player to look at the gun on the ground, press a key and have it be parented to the empty? I would also like for the player's old gun to drop on the floor where the one being picked up was and un-parent from the empty when the new gun is picked up. If you want an example I guess you could say it is like halo where you can go around and pick up new guns. I am not looking to make an inventory, just a simple script where you can swap your weapon.

• You should add the Unity tag. – LinkWindcrafter May 2 '18 at 21:42
• gun.transform.setParent(reference_to_empty) – Draco18s May 2 '18 at 23:48

Since the condition for picking up a gun is that it is in range (the player is nearby and looking at it) and the players presses a key, you need to maintain a list of all the guns close enough to pick up, and decide how you will choose. The simplest way, as shown here, is to pick whatever was added to the list first, but you could also choose among them based on which is closest to the player.

When the player presses a certain key ("Fire2" as set by the input manager in this case), the currently held gun's parent is unassigned, and the nearby gun takes its place. It's parent becomes whatever this script is attached to. You then move the gun to the hand's position to take it off the ground.

GameObject heldGun;

List<GameObject> nearbyGuns;

void Start() {
//initialize guns. Assume you start not holding a gun.
heldGun = null;
nearbyGuns = new List<GameObject>();
}

//Another gun is close enough to be picked up
void OnTriggerEnter(Collider other) {
if (other.tag == "Gun"  && !nearbyGuns.Contains(other.gameObject)) {
}
}

//The player walked away; can no longer pick up the gun
void OnTriggerExit(Collider other) {
if (nearbyGuns.Contains(other.gameObject)) {
nearbyGuns.Remove(other.gameObject);
}
}

void Update() {
//Check if key is pressed and a gun is nearby
if (Input.GetButtonDown("Fire2") && nearbyGuns.Count > 0) {
//drop any held gun
if (heldGun != null)
heldGun.transform.parent = null;
//new gun is held
heldGun = nearbyGuns[0];
//held gun no longer on ground
nearbyGuns.Remove(heldGun);
heldGun.transform.parent = transform;
//put held gun in hand
heldGun.transform.position = handPosition;
}
}


To make this work, you'll need to set handPosition to the local position of the hand. You'll also need to put a trigger collider on the player/camera. Position it so that anything in the trigger can be picked up.

• A better solution would be to pick up the gun the player's crosshair is pointing at, but this script should be enough to get the question author going. – Philipp Jun 7 '18 at 15:12