Gun Sway Script Not Working Properly on Start

Hi,

I found this helpful gun sway script on the here that was posted as an answer, but there’s one issue I have been trying to fix with it for hours. On start up I get:

   NullReferenceException: Object reference not set to an instance of an object

It has to do with the function start on the script below, but it’s getting the local position so I don’t know why it errors. If I play past the error by unpausing it, it works perfectly. I’m very confused by this, does anyone know why?

Here’s the code:

public var MoveAmount : float = 1;

public var MoveSpeed : float = 2;

public var GUN: GameObject;

public var MoveOnX : float;

public var MoveOnY : float;

public var DefaultPos : Vector3;

public var NewGunPos : Vector3;

function Start(){

DefaultPos = transform.localposition;   

}

function Update () {

MoveOnX = Input.GetAxis("Mouse X") * Time.deltaTime * MoveAmount;

MoveOnY = Input.GetAxis("Mouse Y") * Time.deltaTime * MoveAmount;

NewGunPos = new Vector3 (DefaultPos.x+MoveOnX, DefaultPos.y+MoveOnY, DefaultPos.z);

GUN.transform.localPosition = Vector3.Lerp(GUN.transform.localPosition, NewGunPos, 
MoveSpeed*Time.deltaTime);

  }

The only reference in your script that can be null is the GUN object. Verify that you have set the reference in the editor.