Home > Net >  Function not completing updating variables in the Script Unity C#
Function not completing updating variables in the Script Unity C#

Time:08-26

I'm newish to unity and I have come into a problem which I have no idea how to fix or even what is going wrong. My public void function is getting variables in from another script and updating them but when it is called in the update function, those variables are not updating and are instead logging 0.

public void statsImport(float XPImport)
    {
        float XPlevel = XPImport; 
        Debug.Log(XPlevel); 
    }
void Update()
    {
        Debug.Log(XPlevel);
    }

When Debug.Log is called this happens showing that it is not updating the variable.

Any help would be appreciated thanks.

CodePudding user response:

I suggest you spend some time reading about variable scoping in C#. You can think of these as blocks enclosed by { }.

When you declare a variable inside of a scope (such as with float XPlevel = XPImport), that variable only exists inside of that scope:

public void statsImport(float XPImport)
{
    // start new method scope

    // declare variable `XPlevel` inside of that scope
    float XPlevel = XPImport; 
}

void Update()
{
    // start new method scope

    // `XPlevel` doesn't exist here
    Debug.Log(XPlevel);
}

Instead, what you probably want is something like this, where you make XPlevel a field inside of the class-scope:

public class MyComponent : MonoBehaviour
{
    // declare class-level field
    private float XPlevel;

    public void statsImport(float XPImport)
    {
        // `XPlevel` exists here
        XPlevel = XPImport; 
    }

    private void Update()
    {
        // `XPlevel` exists here
        Debug.Log(XPlevel);
    }
}

If you want to be able to edit the value of XPlevel inside of the Editor, add the [SerializeField] tag. This has the same effect as making XPlevel public, but only allowing the field to be set inside of your script:

[SerializeField]
private float XPlevel;

Once you're comfortable with that, you could also make XPlevel a property instead:

[field: SerializeField]
public float XPlevel { get; private set; }
  • Related