Search code examples
scriptingunity-game-engineunityscript

Share data between scripts?


I want to create a scoring system. I have 4 buttons with 4 different but similar scripts and want to share 1 GUI Text for the scores. Example Code:

var something : Sprite;
var SpriteRenderer : SpriteRenderer;
var score : int = 0;
var guiScore : GUIText;

function OnMouseDown () {
    if(SpriteRenderer.sprite == something) {
        score += 1;
        guiScore.text = "Score: " = score;
    }
}

Right now, if I pressed a button and got a point then I pressed a different button the score would start from 0 again. How can I share data something like static variables but different scripts? I know this sounds a bit noobie but any help would be much appreciated. Thanks in advance


Solution

  • Static variables won't appear in the inspector so you can't assign the GUIText in the inspector (thanks for making me find out). So try using GetComponent instead:

    // make a variable of type GUIText
    var guiScore: GUIText;
    
    // assign the gameobject in the inspector
    var staticObject: GameObject; 
    
    // Again I don't know the name of your script, so I'll name it StaticScript
    // get the script
    StaticScript scr = staticObject.GetComponent(StaticScript); 
    
    // assign local GUIText with the one from above
    guiScore = scr.guiScore; 
    

    This way you have already shared 1 GUIText for all other scripts.

    However you said:

    Right now, if I pressed a button and got a point then I pressed a different button the score would start from 0 again

    Doesn't that mean something is wrong with the score, not the GUIText?