Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
  1. Attach script to the player game object
  2. Add an empty child game object to the player game object, this object functions essentially as the player's hands. The transform is used to set the position of the picked up item.
  3. Create a new layer and assign any game objects that can be picked up to this layer
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CanPickupObjects : MonoBehaviour
{
public LayerMask clickableLayer;
public GameObject currentlyHolding;
public GameObject pickupDestination;
private BoxCollider thisCollider;
public void Start()
{
this.thisCollider = this.GetComponent<BoxCollider>();
}
public Vector3 raycastOrigin
{
get
{
return new Vector3(transform.position.x, transform.position.y + .5f, transform.position.z);
}
}
public void Update()
{
if (Input.GetMouseButtonDown(0))
{
var clickedObject = this.GetClickedObject();
if (clickedObject != false)
{
this.PickUpItem(clickedObject);
}
}
if (Input.GetMouseButtonDown(1))
{
this.DropItem();
}
}
private dynamic GetClickedObject()
{
RaycastHit mouseHit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out mouseHit, 50, this.clickableLayer.value))
{
return mouseHit.collider.gameObject;
}
return false;
}
private bool IsItemReachable(GameObject item)
{
return this.thisCollider.bounds.Intersects(item.GetComponent<BoxCollider>().bounds);
}
public void PickUpItem(GameObject item)
{
if (!this.IsItemReachable(item))
{
return;
}
Rigidbody rb = item.GetComponent<Rigidbody>();
rb.useGravity = false;
rb.constraints = RigidbodyConstraints.FreezeAll;
item.GetComponent<BoxCollider>().enabled = false;
item.transform.parent = this.gameObject.transform;
item.transform.transform.rotation = this.pickupDestination.transform.rotation;
item.transform.transform.position = this.pickupDestination.transform.position;
this.currentlyHolding = item;
EventManager.instance.Trigger("itemPickedUp", item.gameObject.name);
}
public void DropItem()
{
if (this.currentlyHolding == null)
{
return;
}
Rigidbody rb = this.currentlyHolding.GetComponent<Rigidbody>();
rb.useGravity = true;
rb.constraints = RigidbodyConstraints.None;
this.currentlyHolding.transform.parent = null;
this.currentlyHolding.GetComponent<BoxCollider>().enabled = true;
this.currentlyHolding = null;
EventManager.instance.Trigger("itemDropped");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.