Getting Score Each Time Key is Destroyed

Hello

Each time I destroy a key by clicking on it, I want the Gui Text to show the score go up by one, and for the object to be destroyed, and at the end of the game, for the score to carry over to the winning scene or the losing scene. So I have to scripts, one is the Score Script, and it is attached to a Gui Text, displaying it on the screen. The other script is the one attached to the keys, and it is supposed to destroy the object and improve the score, but it is not doing either. I also do not know how to save the scores for the next level. Please Help.

Score Script:

#pragma strict
 var Score3dText: UnityEngine.UI.Text;
var score=1000;
function Update(){
    Score3dText.text="Score : " + score.ToString();
}

Here is the Key Destroy and Score Script:

private var Score3Dtext: GameObject;
function Start(){
    Score3Dtext= GameObject.FindGameObjectWithTag("ScoreBoard") ;
 
}
  
function Update () {
  
    if(Input.GetMouseButtonDown(0))
  
    {
  
        var hit: RaycastHit;
  
        var ray: Ray=Camera.main.ScreenPointToRay (Input.mousePosition);
  
  
  
        if(Physics.Raycast(ray, hit))
  
        {
  
            if(hit.transform.gameObject == this.gameObject)
  
            {
                Score3Dtext.GetComponent(Score).score+=1;
                Destroy(this.gameObject);
  
            }
  
        }
  
    }
}

I would use a Game Manager (or Score Manager, call it however you like).
You can have it in all your scenes and access it from every other class.
I’m sorry I’m not coding in JavaScript but I can show you an example in C#.

How I would do it:

  • Create a Game Manager with your score variable in it.
  • Attach the ray casting script to the main camera, NOT to the key object.
  • After ray hits a key, destroy that key (or maybe deactivate it) and add a point to your score (gameManager.instance.myScore += 1)
  • Update your GUI text to show gameManager.instance.myScore

Same way you can display your score in the final scene by just accessing the score variable inside your gameManager.