I am having problems with a weapon pick up system(More specifically the detection of weapons)

Hello,
I am having problems with a weapon pick up system in my game.
I think it’s a raycast problem since after testing i tried printing “weapon selected”
if the raycast hits the weapon.
If anyone has any ideas on how to fix this please share it.
Thank you.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InteracionManager : MonoBehaviour
{
    public static InteracionManager Instance { get;  set; }


    public Weapon hoveredWeapon = null;

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
        }
        else { Instance = this; }
    }

    private void Update()
    {
        Ray ray = Camera.main.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit)) 
        {
            GameObject objectHitByRaycast = hit.transform.gameObject;

            if (objectHitByRaycast.GetComponent<Weapon>())
            {
                print("WeaponSelected");
                hoveredWeapon = objectHitByRaycast.gameObject.GetComponent<Weapon>();
                hoveredWeapon.GetComponent<Outline>().enabled = true;

                if (Input.GetKeyDown(KeyCode.F))
                {
                    WeaponManager.Instance.PickupWeapon(objectHitByRaycast.gameObject); 
                }
            }
            else
            {
                if (hoveredWeapon) hoveredWeapon.GetComponent<Outline>().enabled = false;
            }
        }
    }
}

You may wish to start with any one of the ten billion existing “weapon pickup in Unity” tutorials out there already on Youtube. No sense in making it up on your own until you’ve at least done it once the correct way!

Otherwise, it just sounds like you wrote a bug… and that means… time to start debugging!

By debugging you can find out exactly what your program is doing so you can fix it.

Use the above techniques to get the information you need in order to reason about what the problem is.

You can also use Debug.Log(...); statements to find out if any of your code is even running. Don’t assume it is.

Once you understand what the problem is, you may begin to reason about a solution to the problem.

1 Like

Thank you for the advice it helped me a lot!