Please use code tags, I’m hurting my eyes looking at that code:
( Using code tags properly )
Also, the title is a bit immature. I suggest you change it to something reasonable
Alright so just from looking at the code, it seems like you want to pick up the gun when the player is looking at the gun?
If that’s the case, then your casting a ray in the wrong direction. Instead of:
var forward = transform.TransformDirection(Vector3.forward);
It should be something like this:
var forward = transform.TransformDirection(playerCamera.transform.forward);
Also, in these lines:
testObj.transform.parent = GameObject.Find("RigidBodyFPSController").transform;
testObj.transform.parent = GameObject.Find("MainCamera").transform;
I don’t understand why you’re setting the parent once, then again, there is no point of setting the parent twice, one after the other.
Also, you should always avoid calling GameObject.Find in the Update function, it’s much better practice to save the reference in the Start function like this:
GameObject mainCam;
void Start () {
mainCam = GameObject.Find("MainCamera");
}
And then when setting the parent do this:
testObj.transform.parent = mainCam.transform;
Let me know if you want me to make something clearer.
For those who would actually like to read his code, here it is properly formatted:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Raycasting : MonoBehaviour {
GameObject testObj;
bool canHover = false;
public Transform onhand;
public bool isHolding;
private void Update()
{
var forward = transform.TransformDirection(Vector3.forward);
RaycastHit hit;
if (Physics.Raycast(transform.position, forward, out hit))
{
if (hit.distance <= 5.0f && hit.collider.gameObject.tag == "pickupobject")
{
canHover = true;
testObj = hit.transform.gameObject;
if (isHolding == true)
{
testObj.GetComponent<Rigidbody>().useGravity = false;
testObj.transform.position = onhand.position;
testObj.transform.parent = GameObject.Find("RigidBodyFPSController").transform;
testObj.transform.parent = GameObject.Find("MainCamera").transform;
Debug.Log(testObj.name);
isHolding = true;
}
if (Input.GetButtonDown("e"))
{
isHolding = true;
}
if (isHolding == true && Input.GetButtonDown("e"))
{
testObj.transform.parent = null;
testObj.GetComponent<Rigidbody>().useGravity = true;
isHolding = false;
}
}
else
{
canHover = false;
}
}
}
private void OnGUI()
{
if (canHover == true)
{
GUI.Box(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 100, 150, 20), "Pick Me Up");
}
}
}