
It looks like you're new here. If you want to get involved, click one of these buttons!
I am making a weapon pick up and drop script, I can drop the weapon but not pick it up.
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponPickUpScript : MonoBehaviour
{
public Gun gunScript;
public Rigidbody rb;
public BoxCollider coll;
public Transform player, weaponHolder, fpsCam;
public float pickUpRange;
public float dropForwardForce, dropUpwardForce;
public bool equipped;
public static bool slotFull;
// Use this for initialization
void Start()
{
//setup
if (!equipped)
{
gunScript.enabled = false;
rb.isKinematic = false;
coll.isTrigger = false;
}
if (equipped)
{
gunScript.enabled = true;
rb.isKinematic = true;
coll.isTrigger = true;
slotFull = true;
}
}
// Update is called once per frame
void Update()
{
//check if player is in range and "e" is pressed to pick up weapon.
Vector3 distanceToPlayer = player.position - transform.position;
if (!equipped && distanceToPlayer.magnitude <= pickUpRange && Input.GetKeyDown(KeyCode.E) && slotFull) PickUp();
//Drop if equipped and "q" is pressed
if (equipped && Input.GetKeyDown(KeyCode.Q)) Drop();
}
private void PickUp()
{
equipped = true;
slotFull = true;
//Make weapon child of the camera and move it to default position
transform.SetParent(weaponHolder);
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.Euler(Vector3.zero);
transform.localScale = Vector3.zero;
//Make rigidbody kinematic and boxCollider a trigger
rb.isKinematic = true;
coll.isTrigger = true;
//enable script
gunScript.enabled = true;
}
private void Drop()
{
equipped = false;
slotFull = false;
//set parent to null
transform.SetParent(null);
//Make rigidbody not kinematic and boxCollider normal
rb.isKinematic = false;
coll.isTrigger = false;
//gun carries momentum of player
rb.velocity = player.GetComponent<Rigidbody>().velocity;
rb.AddForce(fpsCam.forward * dropForwardForce, ForceMode.Impulse);
rb.AddForce(fpsCam.up * dropUpwardForce, ForceMode.Impulse);
//add a random rotation when dropping
float random = Random.Range(-1f, 1f);
rb.AddTorque(new Vector3(random, random, random) * 10);
//enable script
gunScript.enabled = false;
}
}