I’m having a problem with my Item Pick up script where the trigger collider activates on every single gameobject it hits, this is a problem because it stops the player from picking up other game objects with this script. Is there anyway I can fix this or exclude certain game objects from activating the trigger?
My code:
public class betterPickup : MonoBehaviour
{
public Transform player;
public Transform playerCam;
public float throwForce = 500;
bool hasPlayer = false;
bool beingCarried = false;
private bool touchedWall = false;
// Update is called once per frame
void Update()
{
//checks the distance between the object being picked up and the player
float dist = Vector3.Distance(gameObject.transform.position, player.position);
/*if the distance is less than 5 units, the object can be picked up, this is to stop the script from
selecting of all game objects that use this script*/
if(dist <= 5f)
{
hasPlayer = true;
}
else
{
hasPlayer = false;
}
if(hasPlayer && Input.GetKeyDown("e"))
{
//if the object can be picked up & the player presses E, the object is parented to the player camera
//isKinematic is true so the game object doesn't fall down once picked up
GetComponent<Rigidbody>().isKinematic = true;
transform.parent = playerCam;
beingCarried = true;
}
if (beingCarried)
{
if (touchedWall)
{
//if the object touches a wall, the player stops carrying the object
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
touchedWall = false;
}
if (Input.GetMouseButtonDown(0))
{
//throwscript
/*same as touchedWall except we add force to the object via playercam forward speed
multiplied by the throwForce so the object go fast*/
//tldr: object go fast if left mouse do clicky clicky
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
GetComponent<Rigidbody>().AddForce(playerCam.forward * throwForce);
}
else if (Input.GetMouseButtonDown(1))
{
//drop script
//right mouse to drop object
GetComponent<Rigidbody>().isKinematic = false;
transform.parent = null;
beingCarried = false;
}
}
}
void OnTriggerEnter()
{
//if the object hits anything, it sets touchedWall to True
//trigger is used because disabling isKinematic also disables collision
if (beingCarried)
{
touchedWall = true;
}
}
}