Unity explains it but I just don’t know how to implement it.
I made a script that lets me pick up the object.The code is going to be in a cube.I just want to be able to pick the object that has this script by holding f button.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pickup : MonoBehaviour
{
bool Isholding=false;
Vector3 Distance;
public GameObject player;
public GameObject collidersGameobject;
void Update()
{
if(Input.GetKeyDown(KeyCode.F)&& is touching collidersGameobject=true )
{
Isholding=true;
Distance=transform.position-collidersGameobject.transform.position;
}
if(Input.GetKeyUp(KeyCode.F))
{
Isholding=false;
}
if(Isholding=true)
{
transform.position=collidersGameobject.transform.position+Distance;
}
}
}
There is no equivalent version of the isTouching function for 3D collision. i suggest using OnTriggerEnter or just detect the distance bewteen the player and the cube and if youre within for example 20f between the cube and the player and you press F the cube will be pick up. in this case make sure the cube has a rigidbody on it. this is an old script of mine that i combined with yours, i havent tested this specifc code but it should work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pickup : MonoBehaviour
{
float throwForce = 400;
Vector3 objectPos;
float distance;
public GameObject cube;
public GameObject playerHand; /// the position you want the cube to be held at
public bool isHolding = false;
void FixedUpdate()
{
distance = Vector3.Distance(item.transform.position, tempParent.transform.position);
if (distance>= 20f)
{
isHolding = false;
}
if (isHolding == true)
{
cube.GetComponent<Rigidbody>().velocity = Vector3.zero;
cube.GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
cube.transform.SetParent(playerHand.transform);
if(Input.GetKeyUp(KeyCode.G)) // this will drop and throw cube - optional
{
cube.GetComponent<Rigidbody>().AddForce(playerHand.transform.forward * throwForce);
isHolding = false;
}
}
else
{
objectPos = cube.transform.position;
cube.transform.SetParent(null);
cube.GetComponent<Rigidbody>().useGravity = true;
cube.transform.position = objectPos;
}
if(Input.GetKeyUp(KeyCode.F) && (distance <= 20f))
{
isHolding = true;
cube.GetComponent<Rigidbody>().useGravity = false;
cube.GetComponent<Rigidbody>().detectCollisions = true;
}
}
Thank you,I am going to create a sphere collider instead of istouching,and then I am going to check if that
object is touching.