hi everyone, i have wierd problem in my script that i’m trying to solve, and i thought some of you may help.
my code isn’t working, because… yes. No, for real, there are no errors or messages in my console, yet the script won’t fire.
Unity engine Version: 6.4
Windows
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class LobbyScript : MonoBehaviour
{
public InputAction Graj;
void Start()
{
Graj = new InputAction(binding: "<Keyboard/Space>");
Graj.performed += Doopa;
SceneManager.LoadScene("Lobby");
}
// Update is called once per frame
void Update()
{
}
void Doopa(InputAction.CallbackContext context)
{
SceneManager.LoadScene("LvlX");
Debug.Log("The Script works");
}
}
maybe you can figure out what’s wrong. If you do, thank you so much!
Did you enable the InputAction? You might have to add Enable() when you create the action:
Graj = new InputAction(binding: "<Keyboard/Space>");
Graj.performed += Doopa;
Graj.Enable();
Firstly, you need to remove or rework this line:
SceneManager.LoadScene("Lobby");
Otherwise, you may end up repeatedly loading the same scene, depending on where this script is attached.
Your binding is also almost correct, but it may not register properly unless you use:
"<Keyboard>/space"
instead of:
"<Keyboard/Space>"
Next, as CiroContns noted, you need to add:
Graj.Enable();
after subscribing to the action:
Graj = new InputAction(binding: "<Keyboard>/space");
Graj.performed += Doopa;
Graj.Enable();
Lastly, make sure that your scenes have been added to the Build Settings.
Otherwise, SceneManager.LoadScene() will not be able to load them. You can add them by dragging them from the Project tab.
The finished code should look like this:
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.SceneManagement;
public class LobbyScript : MonoBehaviour
{
public InputAction Graj;
void Start()
{
Graj = new InputAction(binding: "<Keyboard>/space");
Graj.performed += Doopa;
Graj.Enable();
}
// Update is called once per frame
void Update()
{
}
void Doopa(InputAction.CallbackContext context)
{
Debug.Log("Action Pressed");
SceneManager.LoadScene("LvlX");
Debug.Log("The Script works");
}
void OnDisable()
{
Graj.performed -= Doopa;
Graj.Disable();
}
}
The OnDisable and/or OnDestroy methods are useful practice to avoid subscription clutter.