I'm trying to make a pickup and drop script by myself and every time the game calls the pickup function, it seemed to cause memory leaks and freezes the game for few seconds.
After those few seconds, the items does get picked up but the fps drops significant and the drop function seems to do fine.

*Attached to the Item holder
using UnityEngine;
public class PickupController : MonoBehaviour
{
public GameObject itemHolder;
public bool slotFull;
private GameObject currentObject;
private IPickable pickupScript;
public void PickUp(GameObject pickupObject)
{
if (pickupObject == null)
{
Debug.LogError("Pickup Object is null");
return;
}
slotFull = true;
currentObject = pickupObject;
pickupScript = pickupObject.GetComponentInChildren<IPickable>(); //I'm trying to get the WheelRange.cs script
Debug.Log(pickupObject.gameObject.name);
if (pickupScript == null)
{
Debug.LogError("pickupScript is null.");
return;
}
currentObject.transform.SetParent(itemHolder.transform);
pickupScript.OnItemPickup();
currentObject.transform.localPosition = Vector3.zero;
currentObject.transform.localRotation = Quaternion.identity;
}
public void Drop()
{
slotFull = false;
currentObject.transform.SetParent(null); //Removes the parent
pickupScript.OnItemDrop();
}
}
*Attached to WheelRange gameobject
using UnityEngine;
public class WheelRange : MonoBehaviour, IPickable
{
[SerializeField] private Canvas canvas;
[SerializeField] private BoxCollider boxCollider;
[SerializeField] private PickupController pickupScript;
private GameObject parentObject;
private bool beingUsed;
private float distToGround;
void Start()
{
beingUsed = false;
canvas.gameObject.SetActive(false);
parentObject = this.transform.parent.gameObject; //Gets the actual wheel gameobject
distToGround = boxCollider.bounds.extents.y;
}
public void OnItemPickup()
{
beingUsed = true;
pickupScript.PickUp(parentObject);
boxCollider.gameObject.SetActive(false);
canvas.gameObject.SetActive(false);
}
public void OnItemDrop()
{
beingUsed = false;
boxCollider.gameObject.SetActive(true);
}
//Rest of these functions probably doesn't apply to the error
bool IsGrounded()
{
return Physics.Raycast(parentObject.transform.position, Vector3.down, distToGround + 0.1f);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player") canvas.gameObject.SetActive(true);
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player") canvas.gameObject.SetActive(false);
}
}
The interface
public interface IPickable
{
void OnItemPickup();
void OnItemDrop();
}
IsGroundedand it looks like you have a circular reference sinceOnItemPickupcallspickupScript.PickUpand inPickUpyou callpickupScript.OnItemPickup()\$\endgroup\$IsGroundedfunction isn't being used yet. I didn't see the circular reference there, and after removing thepickupScript.OnItemPickup()line from the PickupController, everything works fine now. Thank you \$\endgroup\$