Trying to share two variables between two scripts for score system.

Hello, I am currently trying to make a side scrolling space shooter and current implementing a scoring system. At the moment I have two things that spawn. An enemy and an asteroid.

I have got my scripts working individually. So essentially when I destroy an enemy it sends a number to the GUIText and then when destroying an asteroid it sends a number to the same GUIText.

I am trying to make it so that the GUIText both adds up the enemies and asteroids score. Could anyone help?

Thank you!

(Some sample code)

using UnityEngine;
using System.Collections;

public class ScoreController : MonoBehaviour {

	public GUIText scoreText;
	private int score;

	void Start()
	{
		score = 0;
	}

	public void AddScore(int newScoreValue)
	{
		score += newScoreValue;
		UpdateScore();
	}

	void UpdateScore()
	{
		scoreText.text = "Score: " + score;
	}

}

void Start()
{
	GameObject gameControllerObject = GameObject.FindWithTag("GameController");
	if(gameControllerObject != null)
	{
		gameController = gameControllerObject.GetComponent <ScoreController>();
	}

	else if(gameControllerObject == null)
	{
		Debug.Log ("Could not find game object controller.");
	}

}

You can store that value using “PlayerPrefs” and access where you want. That value will be same doesn’t matter from which object you are accessing.

PlayerPrefs Reference

declare access level to public in ScoreController, then in your other script that needs to use the value of ScoreController.score, call the script and use the variable

ie

GameObject.Find("GameObjectThatHaveScoreControllerOnIt").GetComponent<ScoreController>().score;

If there is only ever going to be one player/score at a time, you can store the Score as a public static variable (public static int Score) and reference it from your scripts:

Destroyed() {
  ScoreController.Score += scoreValue;
}

//Where scoreValue is a private int defined in the enemy.asteroid class.