What is your own method to share data between script ?

Hi,

When you have some datas (by data I mean variables) you want share them in many scripts, what do you do ?

I don’t know if I should create a static class to gather all datas or create a Script and attach it to a kind of “Master GameObject” in my scene and catch him after with GetComponent() ?

None of these two methods seems right to me… so what is your own method to share data between script ?

Actually, if you have a static class and use static variables you don’t have to “find” it or use GetComponent(). You can access the vars directly through the classname. At least that’s the way I do it. You might want to take a look at a Singleton approach:

Actually, this can be done quite easily. The solution can be found here: Referencing non static variables from another script? C# - Unity Answers
I certainly found it extremely helpful, and it should answer your question.

In a nutshell, make the variable you want to access from the other script public like this:

public float myVariable = 3.14159;

Then, you need to put this code in the script that will be acessing that public variable

private float myOtherVariable;
private GameObject gameObjectWithVariable;

void Start() 
{
    gameObjectWithVariable = GameObject.Find("TheNameOfTheGameObjectThatContainsTheScriptWithTheVariableYouWant");
    myOtherVariable = GetComponent<TheNameOfTheScriptThatContainsThePublicVariable>().myVariable;
}
void Update() {
    myOtherVariable = GetComponent<TheNameOfTheScriptThatContainsThePublicVariable>().myVariable;
    Debug.Log(myOtherVariable);
}

The update block is only necessary if you need to detect changes in the variable. If you just need to access it once, only having it in the Start() block will work.

Depending on what objects you are talking about you can get the references to significant game objects on startup or instantiation and keep those references in memory.

Then you can call methods on those objects or set properties/ fields on those objects to pass data between them.


Static members and singletons should be used sparingly (i.e. when appropriate) as they can cause all sorts of issues with threading and breaking the testability of your codebase.

If you really want to use them then at least consider using an IoC container and injecting them into your components as needed.


Let me know if any of that is unclear and I can provide examples.