Hello! I have two scripts, one to initialize an object, a second to pick it up with the player by pressing E and colliding with the initialized object. The problem is, now the object gets initialized, but if I press E again, the player picks it up, a new object gets automatically initialized and the status of the object the player carries, is null, so he can’t drop it anymore. Does anybody know, what’s wrong in the scripts below, I would be very thankful!
// PLAYER SCRIPT
Rigidbody rigidBody;
public GameObject tempParent;
public Transform carryPosition;
ObjectBase object;
bool carrying;
Renderer rend;
GameObject pickupObject;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (pickupObject != null && !carrying)
{
pickup();
carrying = true;
}
else if (pickupObject != null && carrying)
drop();
}
}
public void pickup()
{
pickupObject.GetComponent<Rigidbody>().useGravity = false;
pickupObject.GetComponent<Rigidbody>().isKinematic = true;
pickupObject.transform.position = carryPosition.transform.position;
pickupObject.transform.rotation = carryPosition.transform.rotation;
pickupObject.transform.parent = tempParent.transform;
}
void drop()
{
pickupObject.GetComponent<Rigidbody>().useGravity = true;
pickupObject.GetComponent<Rigidbody>().isKinematic = false;
pickupObject.transform.parent = null;
pickupObject.transform.position = carryPosition.transform.position;
}
public bool isPlayerCarrying()
{
return carrying;
}
public GameObject getPickupObject()
{
return pickupObject;
}
void OnTriggerEnter(Collider other)
{
ObjectBase object = other.GetComponent<ObjectBase>();
if (object != null)
{
pickupObject = other.gameObject;
}
}
void OnTriggerExit(Collider other)
{
if (pickupObject != null)
{
pickupObject = null;
}
}
// ---------------- INSTANTIATE SCRIPT ----------------------
public Rigidbody drug;
public Transform spawnPoint;
private bool isCarrying;
private bool isNearObject = false;
void Update()
{
isCarrying = GameObject.Find("PlayerMovement").GetComponent<PlayerAction>().isPlayerCarrying();
if (!isCarrying && isNearObject && Input.GetKeyDown(KeyCode.E))
{
Instantiate(drug, spawnPoint.position, spawnPoint.rotation);
}
}
void OnTriggerEnter(Collider other)
{
isNearObject = true;
}
void OnTriggerExit()
{
isNearObject = false;
}