What am I doing wrong when disabling a script?

Here is my code, i simply want to disable a script upon startup but I’m having serious issues with it. I’ve been following another post enable/disable script from another script c#? - Unity Answers

I’m following it step by step but still seem to be having trouble :confused:

Here is the code:

public moveTowardsPlayer movement;

	void Start()
	{
		movement = GetComponent<moveTowardsPlayer>();
		movement.enabled = false;
	}

I just want to disable the moveTowardsPlayer script when the scene begins but I get this error: Object reference not set to an instance of an object

Can anyone shed some light for me?

The problem here is that your moveTowardsPlayer script MUST be present on the same game object that this script is attached to due to the reason that GetComponent retrieves a component from ‘this’ gameObject.

If GetComponent does not find a script it returns null, therefore when you do movement.enabled = false; movement does not have a reference therefore giving you the object reference error.

The solution to this is to first retrieve the gameObject that moveTowardsPlayer is present on, and then disable the script.

movement = GameObject.Find("Player").GetComponent<moveTowardsPlayer>();
movement.enabled = false;