In the code I'm doing, I usually use global and local variables, as recommended.

If the variable is not going to be used in more than any method, I make it local, otherwise, I make it global.

In addition to using local variables with things that don't happen all the time, but every now and then. The player's shot for example: receives the value of a script that contains the player's data.

But I know that this isn't always clear, especially since I'm working on Unity.

**Suppose the following situation:**

I usually separate scripts by function, so I know exactly where to look when I want to modify something and also to completely replace it if I want to.

* script\_admGame - in this script will be the player's health, damage and movement speed;
* script\_playerMovement - in this script is that the character's movement will be programmed, taking the variable from the other script (script\_admGame);

```css
void Update()
{
    if (Input.GetKey(KeyCode.W))
    {
        GameObject obj_adm = GameObject.Find("obj_adm");
        int moveSpeed = obj_adm.GetComponent<script_admGameControl>().moveSpeed;

        //any example
        transform.position += new Vector3(0,0,moveSpeed * Time.DeltaTime);
    }
}
```

**I have two fears:**

* be making minimal and irrelevant optimization savings;
* be saving memory, but overloading the processor/cpu;

That's because some functions are expensive to process (I don't know how interesting it is to run a function every frame instead of having one more variable in the script in question).

**Another important thing is that this speed can change if the player collects certain items, so it doesn't have a fixed value.**

As an alternative to the code shown above, I thought of making the character movement public in the script. Which would initially receive the value of script\_admGame and would sporadically undergo modifications when colliding with items, receiving a certain type of attack, etc.

In short, I would like to know precisely when to use each type of variable in unusual situations. Something like a general rule or convention. Or a way to check and compare two different applications.

**Link I read about but didn't give a clear picture of the situation I'm in doubt (pt-br):**

<https://bookdown.org/jessicakubrusly/programacao-estatistica/funcoes-e-var-local.html>

<https://docs.microsoft.com/pt-br/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables>