I’m having trouble getting an object to pick up into the player’s inventory class! I’ll paste my code below…
For an overview, Pickup objects have a trigger range, that the player should notice when entering. When that happens, I want the player to read if they can pick that object up, pick it up, and remove the object from the scene…
I’ve had some coding experience, but I’m new to scripting, so the setup is still very confusing for me :(.
This code should work with multiple objects, once I add more to the game… I may re-use it for some Enemy AI functions as well.
Any help is appreciated!
using UnityEngine;
using System.Collections;
public class ThePlayerInventory : MonoBehaviour
{
public int pickupObjectsHeld;
public bool canGet;
GameObject Target;
// Update is called once per frame
void Start()
{
pickupObjectsHeld = 0;
canGet = false;
}
void onTriggerStay(Collider other)
{
if (other.transform.tag == "PickUpObject1")
{
canGet = true;
Target = other.gameObject;
}
}
void Update()
{
onTriggerStay(Target);
if (Input.GetButton("Use/PickUp"))
{
if (canGet)
{
pickupObjectsHeld += 1;
canGet = false;
Destroy(Target, 0);
}
}
}
}
You’ve ment OnTriggerStay and not onTriggerStay (upper case first letter).
You should not call OnTriggerStay by yourself. It is a monobehaviour function that will be called by unity if the game object to which this script is attached to has a collider attached to it and if the “other” collider is a collider too (one or both of them need to be a rigidbody/charactercontroller).
You probably need to use OnTriggerEnter and not OnTriggerStay so this is called only when the collision is first identify when objects enter it (and not while they are in it).
So your script would be something like this:
using UnityEngine;
using System.Collections;
public class ThePlayerInventory : MonoBehaviour
{
public int pickupObjectsHeld;
public bool canGet;
GameObject Target;
// Update is called once per frame
void Start()
{
pickupObjectsHeld = 0;
canGet = false;
}
void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "PickUpObject1")
{
canGet = true;
Target = other.gameObject;
}
}
void Update()
{
if (Input.GetButton("Use/PickUp"))
{
if (canGet)
{
pickupObjectsHeld += 1;
canGet = false;
Destroy(Target, 0);
}
}
}
}
IF you will have a tag for different types of pickups, say:
“PuckUpObject1”, “PickupObject2” etc…
You can do:
void OnTriggerEnter(Collider other)
{
switch ( other.transform.tag )
{
case "PickUpObject1":
case "PickUpObject2":
case "PickUpObject3":
canGet = true;
Target = other.gameObject;
break;
}
}