I’m currently working on a trash pickup system for my game, and I’m encountering an issue with the raycast and object activation functionality in my script. I would appreciate any help or insights you can provide to help me resolve this problem.
I have a Trashpickup script attached to my FPS controller, which is responsible for detecting a key press (E) and performing a raycast from the player’s camera position. The goal is to enable a Trash object when the raycast hits it. However, despite verifying the layer setup, collider setup, raycast distance, and camera setup, the object doesn’t appear when I press the key.
What I’ve tried:
Verified the layer setup: The raycastLayerMask includes the correct layer assigned to the Trash object.
Checked the collider setup: The Trash object has a collider component attached to it and is not marked as a trigger.
Adjusted raycast distance: Increased the raycastDistance value to ensure it covers the distance between the player and the Trash object.
Confirmed camera setup: The correct camera is assigned to the playerCamera variable in the Inspector of the Trashpickup script.
Code snippet:
// Relevant code snippet
// ...
private void Start()
{
Trash.SetActive(false);
}
void Update()
{
if (Input.GetKeyUp(KeyCode.E))
{
Ray ray = playerCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, raycastDistance, raycastLayerMask))
{
if (hit.collider.gameObject == Trash)
{
Trash.SetActive(true);
}
}
}
}
I kindly request your assistance in identifying the possible causes of the issue and helping me find a solution. Is there anything I might be missing or any suggestions you can provide to troubleshoot and resolve this problem?
This seems suspect: if (hit.collider.gameObject == Trash)
It seems like you’re trying to hardcode/assign in the inspector the trash object? That makes little sense. It assumes there is only one such object in the whole game, and that you already have a direct reference to it. It would be better to simply check the object for a tag or the existence of a component rather than checking for exact equality to a specific GameObject reference.
Add some Debug.Logs to make sure the code is at least getting to that point and to check which object if any the raycast is actually hitting.
I understand why you were confused. The GameObject named “Trash” that I was referring to is the object held by the player. Through raycasting on another object, it disables that object while enabling an object with the same mesh in the player’s hand, thus mimicking an inventory system.