Trying to freeze Game Object when other Game Object is inactive gives error

Hello, I’m making a game with moving platforms that the player turns on and off. When the moving platforms turn off, they deactivate and the platforms freeze (probably a better way to do that but it’s for a school project due soon so it doesn’t need to be perfect). I want the moving platforms to have a shadow that stops when the original platform is inactive, and the code looks like this:

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

public class StopMovingShadows : MonoBehaviour
{
    // counterpart is the real moving platform
    public GameObject counterpart;
    private Rigidbody2D rb;

    void Start()
    {
       
    }

    void Update()
    {
        if (counterpart.activeSelf == false)
        {
            rb.constraints = RigidbodyConstraints2D.FreezePosition;
        }
        else if (counterpart.activeSelf == true)
        {
            rb.constraints = RigidbodyConstraints2D.None;
        }
    }
}

When I hit play, I’m spammed with errors saying “Object reference not set to an instance of an object” directed at line 24:
rb.constraints = RigidbodyConstraints2D.None; Does anyone know what’s happening?

There’s nothing in the code above that assigns anything to rb hence the null errors.

Make the field public, or decorate it with the SerializeField attribute, and assign it in the inspector.

No matter how many times you get spammed by this error, the answer to fix it is ALWAYS THE SAME.

ALWAYS.

It’s such a common error and so easy to fix we have a pinned post.

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Steps to success:

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

Wow, I can’t believe I missed that, thank you!