Null exception when trying to enable scripts

I have to two scripts Movement and ChangeControl. I am trying to enable and disable Movement.cs from ChangeControl.cs when LeftShift or RightShift is presses. When I press the key, I get a runtime null exception saying “Object reference not set to an instance of the object”. I have basic knowledge of C# and I believe its because scriptMovement has null values. but why ?

using UnityEngine;
using System.Collections;

public class ChangeControl : MonoBehaviour {

	public Movement scriptMovement;
	// Use this for initialization
	void Start () {
	
		scriptMovement = GetComponent<Movement>();

	}
	
	// Update is called once per frame
	void Update () {
		scriptMovement = GetComponent<Movement>();
		if (Input.GetKey (KeyCode.LeftShift)) {
						scriptMovement.enabled = true;		
				} else
			if (Input.GetKey (KeyCode.RightShift))
						scriptMovement.enabled = false;
	}
}

1 Answer

1

Its solved now. I hadn’t added ChangeControl.cs to all the objects. I did that and its working. Thanks a lot!