I am making a game and I have an inventory where you press E in the trigger zone but for some reason first, almost every object in the area comes, then it either disappears completely or it just floats away through the floor, wall, or roof.this is my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUp : MonoBehaviour
{
public Transform theDestination;
void OnTriggerStay()
{
if (Input.GetKeyDown(KeyCode.E))
{
GetComponent<Rigidbody>().useGravity = false;
this.transform.position = theDestination.transform.position;
this.transform.parent = GameObject.Find("Thedestination").transform;
}
void Update ()
{
if (Input.GetMouseButtonDown(1))
{
this.transform.parent = null;
GetComponent<Rigidbody>().useGravity = true;
}
}}}
can anyone help/ tell me why it is happening?
Thanks in advance,
If the objects you’re picking up all have this behaviour and they all happen to be calling OnTriggerStay
(no matter what object is causing them to “trigger”), they will all perform the same action of changing their position to the theDestination.transform.position
value. Likewise, when doing Input.GetMouseButton(1)
all the objects that were just gathered to the destination point will lose their parent and receive gravity again.
You can fix this by ensuring that the object is triggering with the correct trigger-er.
private void OnTriggerEnter(Collider other)
{
if (other.gameObject == <the-correct-object-you-want-to-check-for>)
{
DoPickupStuff();
}
}
I’m curious how you’ve set up the project though, as changing the layer collisions could potentially change my answer (and reasoning why things float through other things).
Also, what’s the difference between public Transform theDestination
and then calling GameObject.Find("Thedestination").transform
? Are those two different objects that have the same-ish name? If you have a reference to the destination object why are you trying to find it again?
@austephner I realized that I just forgot about the fact that I was going to use the public Transform and used gameobject.find instead… so that’s the answer to one of the questions. But I can’t work on it right now because unity kind of broke it’s self so I have to fix it first