getComponent - NullReferenceException

I am trying to create a script where when I click a UI button it changes a speed variable in another script. My code is below but it throws up this error

NullReferenceException: Object reference not set to an instance of an object
Done.pathDone (Int32 newSpeed) (at Assets/Scripts_Custom/Done.cs:9)

I can see when the button is pressed the gameObject is removed from the inspector on the Done script

anybody have any thoughts or solutions to this using Unity 5?

using UnityEngine;
using System.Collections;

public class Done : MonoBehaviour {
	
	public Player Player;
	public void pathDone(int newSpeed) {
		Player = gameObject.GetComponent("Player") as Player;
		Player.speed = newSpeed;
	}
}

You could use the generic function

Player = gameObject.GetComponent<Player>() as Player;

managed to get it working my solution is below

using UnityEngine;
using System.Collections;

public class Done : MonoBehaviour {
	
	public Player player;
	public void pathDone(int newSpeed) {
		player = GameObject.Find("Character").GetComponent<Player>() as Player;
		player.speed = newSpeed;
	}
}

The reason you would get a null reference exception on line 9 is because the call to GetComponent failed to return a player object. The Player member is null therefore Player.speed will throw an exception. You should test for null before using the member.

var player = GetComponent<Player>();
if (player != null) player.speed = newSpeed;

As someone else mentioned, the generic version of GetComponent will return the type specified so casting with ‘as’ is redundant.

Next, as you discovered, the reason GetComponent failed is that you are not attaching the script to the game object that contains the component. You would either need to ‘find’ the correct Player object or, if there is just one, make a public member of type Player and drag the desired Player object onto the field to create a reference. The Find method is very inefficient and should generally only be used in the Start method to cache a reference to the component in your script.

I prefer caching all my references with 'Find’s and 'GetComponent’s (or the …InParent or …InChildren versions) in the start method as ‘dragged references’ can disappear during development (for various reasons, like deleting an object or the serialization problem) and then you have to figure out what was supposed to go in that field.

private void Start()
{
    _player = GameObject.Find("Character").GetComponent<Player>();
}
private Player _player;

Then, in your ‘pathDone’ method you would set the speed as below:

public void pathDone(int newSpeed) 
{
    if (_player == null) return;  // reduce nesting by inverting 'if'
    _player.speed = newSpeed;
 }