Simple static function to display text onscreen (Accessible from anywhere)

Hi everybody,

I want to make a simple function that will accept a string and a number of second to display an information to the player. Responses in JS please. Hi want to be able to call it from any script. So far I created a GUItext object and attached the script below called Message.js

static function Affiche (mess , duree) {
    Debug.Log("Fonction active!!!");
    var component = gameObject.GetComponent(GUIText);
    component.enabled = true;
    component.text = mess;
    yield WaitForSeconds(duree);
    component.enabled = false;
}

and then I can call it like this from any script in my game

Message.Affiche ("Vous avez gagn",5);

I can see that the function is called because of the Debug.Log (if I put everything else in comments). I get the error:

Assets/SCRIPTS/Message.js(4,25): BCE0020: An instance of type 'UnityEngine.Component' is required to access non static member 'gameObject'.

I'm lost, help me please!

Bonjour Jean-luc,

Ok, One way to do that and have access to normal functions like Yield is to use a singleton:

you can find the template for a singleton here

here is Message.js

// since we want to access a guiText, we make it mandatory to avoid errors
@script RequireComponent( GUIText )

// based on http://www.unifycommunity.com/wiki/index.php?title=AManagerClass
//
/// Message is a singleton.
/// To avoid having to manually link an instance to every class that needs it, it has a static variabe called
/// instance, so other objects that need to access it can just call:
///        Message.instance.DoSomeThing();
///
 static var instance : Message;

 // This is where the magic happens.
 //  FindObjectOfType(...) returns the first AManager object in the scene.
 instance =  FindObjectOfType(Message);
 if (instance == null)
     Debug.Log ("Could not locate an Message object. You have to have exactly one Message in the scene.");

 // Ensure that the instance is destroyed when the game is stopped in the editor.
 function OnApplicationQuit() {
     instance = null;
 }

function Affiche(mess:String , duree:float) {
        Debug.Log("Fonction active!!!");
        guiText.enabled = true;
        guiText.text = mess;    
        yield WaitForSeconds(duree);
        guiText.enabled = false;    
}

create a guitext, and attach this script to it.

to test it, create another script that you attach to any gameobject in your scene

calltest.js function Update () {

    if(Input.anyKeyDown){
        Message.instance.Affiche("You have pressed "+Input.inputString,1);
    }

}

The trouble I had with creating a class with a static function is that yield wouldn't work, so I went for a singleton approach.

Hope it helps,

Jean