Having trouble updating the text in my GUI

I am making a tower defense game. I want the total amount of damage dealt to be kept track of. I have a variable called scoreCount where I am storing it in a script that I have named LevelMaster that controls game states and gui updating.

var scoreCount : float = 0;

scoreText.text = "Score: "+scoreCount;

in a second script that I have for my turrets I have this damage function using raycasts

var hit : RaycastHit;
		
			if (Physics.Raycast(rayorigin.position, rayorigin.forward, hit, rayRange, 1<<13)) {
				if(hit.collider != null ){
	    			if (hit.collider.tag == "Ground Enemy") {
	    				hit.collider.SendMessage("TakeDamage", myDamageAmount, SendMessageOptions.DontRequireReceiver);
	    				Debug.Log("projectile fired");
	    				levelMaster.scoreCount += myDamageAmount;
	    				
	    			}
	    			else {
	    				Debug.Log("Hit a different collider");
	    			}
	    		 }
			 }

my issue is in the second script where I have levelMaster.scoreCount += myDamageAmount;

I am getting a NullReferenceException from that line.
I have var levelMaster : LevelMaster; declared at the top of the turret script so it has access to the LevelMaster script.

I want myDamageAmount to be added to the scoreCount variable every time that chunk of code dealing damge is run.

Can anyone tell me what I can do to fix this?

If your variable scoreCount isn’t already both public and static you could do that, which makes it accessible from the second script.

The NullReferenceException can easily be solved by using the function GetComponent(). The way to do that would be to declare a variable in the top of your script.

var levelMaster : LevelMaster;

The above code is what you already have.

In the Start() function you should put the following code.

levelMaster = GetComponent<LevelMaster>();

This should make the reference correct. The above is similar to instantiating a class which is shown below.

var levelMaster = new LevelMaster();

If anything of what I’ve written is wrong, please feel free to correct me. Let me know if this solved your problem.

Declaring the variable does not give you access to the LevelMaster script. You have to initialized ‘levelMaster’. You can do it my first selecting the game object with the obove script and dragging and dropping the game object that has the LevelMaster scrip onto the ‘levelMaster’ variable in this script in the Inspector.

Alternately you could do it dynamically. In start, you can add:

levelMaster = GameObject.Find("NameOfLevelMaterGameObject").GetComponent(LevelMaster);

If you’ve initialized by dragging and dropping and you still get the null reference error, search your Hierarchy to see if you have the above script attached to more than one game object.