So I decided I wanted to make this script part of a separate swap-able weapon so I made a child and put the script there. Before the script worked fine but now it won't work. The script works as follows: if the left mouse button is pressed send a ray cast out forward, if it hits something matching the condition (a tag check, and distance check) parent it to the player, and if the right click button is pressed than un-parent it.
The code:
public class PhysGun : MonoBehaviour
{
public GameObject Player;
private bool isPlayerHolding;
private GameObject RayCastHitObject;
// Update is called once per frame
void Update()
{
Vector3 fwd = transform.forward;
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Input.GetMouseButton(0) && Physics.Raycast(ray, out hit, 10f) && hit.collider.gameObject.CompareTag("Pickable"))
{
Debug.Log("Press detected");
isPlayerHolding = true;
hit.transform.SetParent(Player.transform);
Debug.Log("We hit: " + hit.transform.name);
hit.rigidbody.constraints = RigidbodyConstraints.FreezeAll;
MoveScrollWheel();
}
if (Input.GetMouseButton(1) && Physics.Raycast(ray, out hit, 10f))
{
hit.transform.parent = null;
isPlayerHolding = false;
hit.rigidbody.constraints = RigidbodyConstraints.None;
}
if (isPlayerHolding != false)
{
MoveScrollWheel();
}
}
void MoveScrollWheel ()
{
if (Input.GetAxis("Mouse ScrollWheel") > 0f) // forward
{
Debug.Log("Mouse wheel up");
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0f) // backwards
{
Debug.Log("Mouse wheel down");
}
}
}
What is wrong with my setup?
To clarify a few things...
- It's not working - By this mean it does not parent the object to the player like it should.
- Steps I've taken to resolve the issue (some are already above)...
- Remove tag check requirement - this causes a weird issue no matter where I am it always parents the terrain to the player and causes the player fall through it.
- Manually attach the player GameObject to the script.
- Detach the child (and make it a sibling) and put in front to see if it works that way (it doesn't).
- The raycast is hits something without the tag check (in this case the terrain as described above) but that is totally the wrong thing.
- No error messages appear in the console or anywhere.
- As per request here is a demonstration of the issue.