0

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.

1
  • 2
    You need to set the value to your class level variable, not a new local variable. XPlevel = XPImport. Adding float before that line is creating a local variable called XPlevel which is assigned the value and immediately discarded when the scope ends. Commented Aug 25, 2022 at 0:03

1 Answer 1

0

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; }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that solved it, I was just being a little bit oblivious to C# as a language and trying to exclusively find the problem in Unity. I will definitely read more into variable scoping and C# as a whole, Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.