"Object reference not set to an instance of an object" error

I have a switch and a platform that moves upward when the switch is triggered. I’m getting the error “NullReferenceException: Object reference not set to an instance of an object” when I try to use GetComponent to use the switch’s script in the platform’s code. When I looked up this error message on Unity Answers a lot of people said that it was because Unity couldn’t find a component I needed, so I doublechecked that the switch’s script was attached to the moving platform game object, and it is–however, whenever I press play to run my game, the script disappears. Does anyone know what’s going on? The code for the moving platform is:

using UnityEngine;
using System.Collections;

public class MovingPlatform : MonoBehaviour 
{
 public SwitchScript nearSwitch;
 void Awake ()
 {
 nearSwitch=gameObject.GetComponent<SwitchScript>();
 }
 
 void Update () 
 {
 if (nearSwitch.isSwitched)
 transform.Translate(Vector3.up);
 
 }
}

I plan to add code to stop the platform moving up later, I just need the switch boolean to activate the moving platform.

The code for SwitchScript is

using UnityEngine;
using System.Collections;

public class SwitchScript : MonoBehaviour 
{
 public bool isSwitched=false;

 void OnTriggerEnter (Collider otherObject)
 {
 renderer.material.color=Color.green;
 isSwitched=true;
 
 }
}

Hi TaylorAnderson,

It seems that your problem is that you are trying to Get a component out of the gameObject that has the PlatformScript and not the gameObject that has the SwitchScript, you should try to create a public variable on your platform script which contains the gameObject that has the SwitchScript so then you could use the GetComponent on that object, try something like this:

public class MovingPlatform : MonoBehaviour 
{
 public GameObject switchObject; // <---- in the inspector drag&drop here the gameObject that has the SwitchScript
 public SwitchScript nearSwitch;
 void Awake ()
 {
 nearSwitch=switchObject.GetComponent<SwitchScript>(); //In here change gameObject by switchObject
 }

 void Update () 
 {
 if (nearSwitch.isSwitched)
 transform.Translate(Vector3.up);

 }
}

Now it should work. Try it out and let us know.

This is the code I ended up using, just inside the switch script itself. I’ll leave it here for reference in case any other newbies have the same issue.

using UnityEngine;
using System.Collections;

public class ElevatorSwitchScript : MonoBehaviour 
{
 //all same as doorswitch.
 public bool isSwitched=false;
 
 public float platformUp=5;
 
 public Transform elevator;
 
 public Vector3 desiredPos = new Vector3(0f, 0f, 0f);

 void OnTriggerEnter (Collider otherObject)
 {
 renderer.material.color=Color.green;
 isSwitched=true;
 }
 
 void Update()
 {
 if (isSwitched==true && elevator.transform.position.y <=  desiredPos.y)
 elevator.transform.Translate (Vector3.up * platformUp * Time.deltaTime);
 }
}