Rigidbody returning nullpointerexception despite being set in start method

I am working on a project in which I need to use the rigidbody’s functionality. I declare it at the top of my script like private Rigidbody physics;. And instantiate it in the start method like physics = gameObject.GetComponent<Rigidbody>();. But when I try running one of its methods like AddForce or AddTorque. It gives me a nullpointerexception.

does your gameObject have the Rigidbody Component attached?

Yes

shouldnt make any difference but just it case , test it like this:

physics = GetComponent<Rigidbody>();

Does it have a Rigidbody or a Rigidbody2D attached? They are different classes.

1 Like

No luck.

Do you have more than one instance of this class in your scene at once, like an inadvertent drag-drop on another object that has no Rigidbody?

Try Debug.Log()ing the .name of the GameObject right before the null ref line.

1 Like

Nope, there is only one.

at the end, can you post a picture of the whole script + your hierarchy

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class css_player : MonoBehaviour
{
    private Gyroscope gyro;
    private Quaternion realWorldRot;
    private bool gyroActive;
    private Touch touch;
    private Quaternion baseRot;
    public float maxSwipeTime;
    public float minSwipeDistance;
    private float swipeStartTime;
    private float swipeEndTime;
    private Vector2 swipeStartPos;
    private Vector2 swipeEndPos;
    private float swipeTime;
    private float swipeLength;
    private SphereCollider col;
    Rigidbody physics;
    private bool canJump;
    private bool isDead;
    // Start is called before the first frame update
    void Start()
    {
        enableGyro();
        physics = gameObject.GetComponent<Rigidbody>();
        baseRot = transform.localRotation;
        col = gameObject.GetComponent<SphereCollider>();
        isDead = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (!isDead)
        {
            if (gyro != null)
                realWorldRot = gyro.attitude;
            if (canJump)
            {
                transform.localRotation = new Quaternion(transform.localRotation.x, transform.localRotation.y, (realWorldRot.y*-1), 1) * baseRot;
            }
            else
            {
                transform.localRotation = baseRot;
                transform.position += new Vector3(Input.acceleration.x / 20, 0, 0);
            }
            isSwipe();
            if(transform.localRotation.z>.5 || transform.localRotation.z<-.5)
            {
                isDead = true;
            }
        }
        else
        {
            foreach(GameObject obj in GameObject.FindGameObjectsWithTag("ground"))
            {
                obj.GetComponent<MeshCollider>().enabled = false;
            }
        }
    }

    public void enableGyro()
    {
        if (gyroActive)
            return;
        if(SystemInfo.supportsGyroscope)
        {
            gyro = Input.gyro;
            gyro.enabled = true;
        }
        gyroActive = gyro.enabled;
    }
    private void isSwipe()
    {
        if(Input.touchCount>0)
        {
            touch = Input.GetTouch(0);
            if(touch.phase == TouchPhase.Began)
            {
                swipeStartPos = touch.position;
                swipeStartTime = Time.time;
            }
            else if(touch.phase == TouchPhase.Ended)
            {
                swipeEndPos = touch.position;
                swipeEndTime = Time.time;
                swipeTime = swipeEndTime - swipeStartTime;
                swipeLength = (swipeEndPos - swipeStartPos).magnitude;
                if(swipeTime<maxSwipeTime && swipeLength>minSwipeDistance)
                    swipeControl();
            }
        }
    }
    private void swipeControl()
    {
        Vector2 dist = swipeEndPos - swipeStartPos;
        float xDist = Mathf.Abs(dist.x);
        float yDist = Mathf.Abs(dist.y);
        if ((yDist > xDist) && dist.y > 0)
        {
            if (canJump)
            {
               physics.velocity = (new Vector3(0, 1, 0)  * 5);
            }
           
        }
    }
    private void OnTriggerEnter(Collider collide)
    {
        if(collide.gameObject.tag == "ground") {
            canJump = true;
        }
        if(collide.gameObject.tag == "wind")
        {
           physics.AddTorque(Vector3.right * 100000);
        }
    }
    private void OnTriggerExit(Collider collide)
    {
        canJump = false;
    }
}

6789833--786689--unityObjectInspectorHierarchy .png

I’m 99% sure that OnTriggerEnter can be called before Start gets called. The only place I see you use either AddTorque or AddForce is in OnTriggerEnter, so I’m assuming that’s where you are hitting your error.

Try changing Start to Awake.

Still didn’t work.

maybe disable your colliders until you have got your rigidbody?

Can you post the full error, including line numbers?

NullReferenceException: Object reference not set to an instance of an object
css_player.OnTriggerEnter (UnityEngine.Collider collide) (at Assets/Player/css_player.cs:118)

I am 99.99% sure that you have another instance of css_player floating around in your scene somewhere (it may not exist in your scene file in edit mode, but is instead being instantiated by something). You can search for all instances of it in your scene (in edit & play mode) by typing t:css_player into the hierarchy search bar.

Have you defined Vector3 in Vector3.right * 100000

You mean… the built-in Unity struct, Vector3…?

I think this is the issue. You could confirm by putting a Debug.Log in your Start(), and seeing if that log is posted before or after your NullReferenceException.

3 Likes

You can also search for “T:css_player” in the hierarchy search bar to highlight objects that have a css_player attached to them.

Okay, so get this, it turns out my script wasn’t even finishing the start method, because it got stopped while running my enableGyro() method. I didn’t have my phone connected, so the script was just not setting the gyroscope reference, causing my start method to not go any farther down, so the reference to the rigidbody was not actually being set. I honesty don’t know why I didn’t figure this out earlier. But anyways thanks to everyone for their suggestions and help, sorry I kinda wasted everyone’s time by being a dumbass.

1 Like