I’ve written a code that checks if the character is looking at a gun on the ground. If he is and presses E while doing so it picks the gun up (changes the gun on ground to inactive and gun in hand to active). The code works but for some reason only detects that it’s looking at a gun while the character is moving. Here’s the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LookingRaycast : MonoBehaviour {
public GameObject GunOnGround;
public GameObject GunInHand;
public Camera camera;
RaycastHit hit;
// Update is called once per frame
void FixedUpdate () {
Ray forwardRay = new Ray(camera.transform.position, transform.forward);
if (Physics.Raycast(forwardRay, out hit))
{
if (hit.collider.tag == "Gun")
{
Debug.Log("Gun Hit");
if (Input.GetKeyDown("e"))
{
GunOnGround.SetActive(false);
GunInHand.SetActive(true);
}
}
}
Debug.DrawRay(camera.transform.position, transform.forward * 1000, Color.green);
}
}