Hi, I’m very new to C# and Unity, I’ve been slowly learning it as a new years resolution. I recently set out to make a game which had a bunch of things I wanted to learn. How to make a main menu, crosshair, ect…
I figured this would be the easiest way to learn all the different areas which create a game. My game uses the FPSController, you can pick up objects, throw them with left click, rotate with right click, flick your mouse and let go to also throw. It works perfectly apart from a NullReferenceException. I followed 2 different YouTube tutorials and took bits of code from each tutorial and mashed them together to get what I wanted. Anyway, here’s my Frankenstein code, this is also my first post on here so apologies if I format anything wrong.
This is the line of code which Visual Studio flags up as the issue
previousGrabPosition = carriedObject.transform.position;
And here’s the entire thing.
public class PickupObject : MonoBehaviour {
GameObject mainCamera;
GameObject carriedObject;
Vector3 previousGrabPosition;
Vector3 previousRotatePosition;
public float distance;
public float smooth;
bool carrying;
float chargeTime = 0;
void Start () {
mainCamera = GameObject.FindWithTag("MainCamera");
}
void Update () {
if(carrying) {
carry(carriedObject);
checkDrop();
if (Input.GetMouseButton(1))
{
rotateObject();
}
} else {
pickup();
}
previousGrabPosition = carriedObject.transform.position;
if (Input.GetMouseButton(0))
chargeTime += Time.deltaTime;
if (Input.GetMouseButtonUp(0))
{
float pushForce = chargeTime * 20;
pushForce = Mathf.Clamp(pushForce, 1, 15);
DropObject(pushForce);
chargeTime = 0;
}
}
void rotateObject() {
carriedObject.transform.Rotate(0,4,0);
}
void carry(GameObject o) {
o.transform.position = Vector3.Lerp (o.transform.position, mainCamera.transform.position + mainCamera.transform.forward * distance, Time.deltaTime * smooth);
}
void pickup() {
if (Input.GetKeyDown(KeyCode.E)){
int x = Screen.width / 2;
int y = Screen.height / 2;
Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x,y));
RaycastHit hit;
if(Physics.Raycast(ray, out hit)) {
Pickupable p = hit.collider.GetComponent<Pickupable>();
if(p != null) {
carrying = true;
carriedObject = p.gameObject;
//p.gameObject.rigidbody.isKinematic = true;
p.gameObject.GetComponent<Rigidbody>().useGravity = false;
}
}
}
}
void checkDrop() {
if(Input.GetKeyDown (KeyCode.E)) {
DropObject(0);
}
}
void DropObject(float pushForce)
{
if (carriedObject == null)
return;
Rigidbody rb = carriedObject.gameObject.GetComponent<Rigidbody>();
carrying = false;
rb.useGravity = true;
Vector3 throwVector = carriedObject.transform.position - previousGrabPosition;
float speed = throwVector.magnitude / Time.deltaTime;
Vector3 throwVelocity = speed * throwVector.normalized;
throwVelocity += Camera.main.transform.forward * pushForce;
rb.velocity = throwVelocity;
carriedObject = null;
}
}