0
\$\begingroup\$

I've been working on a 2D RPG and have been trying to make a script that will open or close the public UI element that is selected in properties. I don't receive any errors, but I do receive a warning that says:

Assets\Scripts\KeyManager.cs(7,18): warning CS0414: The field 'KeyManager.activeUI' is assigned but its value is never used

Here's the script that is connected to my canvas:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class KeyManager : MonoBehaviour
{
    private bool activeUI;
    public GameObject UI;

    void Start()
    {
        activeUI = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.I) && (activeUI = false))
        {
            activeUI = true;
            UI.SetActive(true);
        }

        else if (Input.GetKeyDown(KeyCode.I) && (activeUI = true))
        {
            activeUI = false;
            UI.SetActive(false);
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Did you mean to write if ( ... (activeUI == false) ) with two equals signs to do a comparison, rather than a single equals sign to assign a new value to the variable? \$\endgroup\$ – DMGregory Jan 15 at 18:46
2
\$\begingroup\$

This is an syntax error. You compare with == but only one = assigns the value.

The info you get reflects this as well since you only assign the value. You can even shorten the code to something like this

if (Input.GetKeyDown(KeyCode.I)) {
    activeUI = !activeUI;
    UI.SetActive(activeUI);
}

If a condition has twice the same parameter with the same value, you can usually shorten it. The code is flipping the value of activeUI and afterwards assign it to your UI. The info warning about unused activeUI will be gone as well since now we use it.

Now to the info part what your code is actually doing. Consider the following code:

bool toogle = false;
if ((true) && (toogle = true)) Debug.LogFormat("The first toogle print is {0}", toogle);
if ((true) && (toogle = false)) Debug.LogFormat("The second toogle print is {0}", toogle);
Debug.LogFormat("The toogle at the end is {0}", toogle);

When this runs, you would expect that toogle is at the end true, right? But it is actually false. The second condition sets it to false but it does not print the line as well.

Now if we transfer that to your piece of code, you see that the code in your first condition is never executed and only the second piece which closes your UI is working.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.