Can't fix error : "NullReferenceException: Object reference not set to an instance of an object"

I keep getting the following error on a script for this top down follow enemy:
NullReferenceException: Object reference not set to an instance of an object
Trapswan.MovePos (UnityEngine.Vector2 direction) (at Assets/Trapswan.cs:25)
Trapswan.FixedUpdate () (at Assets/Trapswan.cs:30)

Here is the related code:

public class Trapswan : MonoBehaviour
{
    public Transform player;
    private Rigidbody2D rb;
    private Vector2 movement;
    public float moveSpeed = 5f;
    public float SwanHealth = 15f;
   
    void Update()
    {
        Vector3 direction = player.position - transform.position;
        rb = this.GetComponent<Rigidbody2D>();
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        rb.rotation = angle;
        movement = direction;

    }

    void MovePos(Vector2 direction)
    {
        rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime))
        //this is the error causer
    }

    void FixedUpdate()
    {
        MovePos(movement);
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Bullet"))
        {
            damaged();
            Debug.Log("Calling Damaged");
        }

    }

    void damaged()
    {
        SwanHealth = SwanHealth - 1;
        if(SwanHealth <= 0)
        {
            Destroy(gameObject);
        }
    }
}

I’ve looked at other similar issues online and they said the message means that something on the line doesn’t exist, but everything on that line does exist.

Move this rb = this.GetComponent<Rigidbody2D>(); to Start(). You should never use GetComponent() inside of Update. It’s very heavy.

Try doing that and let us know if it helped.

Yeah as @Dextozz said, don’t GetComponent every frame like that. Just do it once in Start or set it with an inspector reference. After you do that it should fix the issue.

You could additionally change MovePos in case you later mess up getting this reference in Start again though.

    void MovePos(Vector2 direction)
    {
        if (rb == null)
        {
            Debug.Log("Trapswan.MovePos was called with rb null, setting rb");
            rb = GetComponent<Rigidbody2D>();
        }
        rb.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime))
        //this is the error causer
    }

I made this post a few days ago and have sense written completely new code to replace this one. I learned in the few days between now and this original post that putting GetCompnent() inside of Update is a BIG NO NO

When you’re making a method, it’s common to have this:

private void MyMethod() {
    if (myComponent == null)
       return;

    //My code goes here.
}

To check if the component is null, that’s if the value isn’t necessarily always going to equal something.

Hello!

Please help.

Unity throws the following error:
NullReferenceException: Object reference not set to an instance of an object
Game_CNT+c__Iterator4.MoveNext () (at Assets/Scripts/Game_CNT.cs:499)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

I have 2 game objects in a scene:

  1. Game_CNT
  2. MP_Scripts

Game_CNT game object has “Game_CNT” script attached to it.
MP_Scripts game object has “MarketingScripts” script attached to it

When I call a method of the “MarketingScripts” from the “Game_CNT” it throws the error above.

Game_CNT:

public class Game_CNT : MonoBehaviour
{

GameObject MP_Scripts; // Get Reference of MP_Scripts

void ShowVideoAd()
{
MP_Scripts.GetComponent<MarketingScripts>().ShowUnityAdVideo(); // This one is in line 499
}

}

MarketingScripts:

public class MarketingScripts : MonoBehaviour
{

  string gameID = "123456";

    void Start()
    {
        Advertisement.Initialize(gameID, true); // Initializing Unity Ads
    }


public void ShowUnityAdVideo() //To show Simple Skippable Video Ads
    {
        if (Advertisement.IsReady("video"))
            Advertisement.Show("video");
        else return;
    }

}

What am I missing here?

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

Fixed it by just creating a new MarketingScripts class variable.
There is actually no need to reference MP_Scripts GameObject.

Game_CNT modified as below:

        //Show Simple Skippable Unity Video Ad

        MarketingScripts mpScript = new MarketingScripts();
        mpScript.ShowUnityAdVideo();