Search Unity

Input between scenes; is there a solution yet?

Discussion in 'Editor & General Support' started by NickVst, Nov 15, 2019.

  1. NickVst

    NickVst

    Joined:
    Feb 17, 2017
    Posts:
    25
    When you switch scenes while holding an input down, that input will be set to 0 in the next scene. That means if you're not specifically working your game around so that your player releases the movement keys, they'll stop until the player re-taps the keys, which in some cases can completely kill the momentum of the game.

    There are three solutions that seem to float around.

    1: Import user32.dll on Windows

    Code (CSharp):
    1. [DllImport("user32.dll")]
    2. public static extern short GetAsyncKeyState(int vkey);
    3.  
    4. void Update() {
    5.     if ( GetAsyncKeyState(0x25 & 8000) > 0)
    6.         Debug.Log("Left key pressed");
    7. }
    • It is hacky to import a DLL for input only
    • You need to know the key codes ahead of time (they're constants, so not a really big problem)
    • No gamepad support
    • Kills cross-platform compatibility

    2: Use additive loading and unload the previous scene


    Code (CSharp):
    1. void Update(){
    2.     velocity.x = Input.GetAxisRaw("Horizontal");
    3.     // Same happens with Input.GetKey().
    4.     if(shouldNewSceneLoad) {
    5.         SceneManager.LoadScene(newScene, LoadSceneMode.Additive);
    6.         SceneManager.UnloadSceneAsync(oldScene);
    7.     }
    8. }
    • Causes weird issues where the old scene won't be unloaded because Unity still thinks it's the active scene
    • Also happens if I set the active scene with
      SceneManager.SetActiveScene()
      .

    3: Put everything in one scene, just far apart
    • Editing this becomes a mess
    • Completely defeats the purpose of scenes as self-contained levels

    I'm currently using method 1, but have there been any better ways to handle this since mid-2018? I did try the new Input system, but it doesn't seem to work in 2019.2.11f1 (perhaps because 2019.2.12 came out?).
     
    Nolex and Sharkbird like this.
  2. MustafaCetin

    MustafaCetin

    Joined:
    Dec 28, 2013
    Posts:
    3
    I had same problem. I tried additive scene loading. Its work but created bad side effects for my project. So i write this script that first unloading old scene later load additive new scene.
    Code (CSharp):
    1.  
    2.     public void load(string scene) {
    3.         var temp = SceneManager.CreateScene("temp");
    4.         SceneManager.UnloadSceneAsync(SceneManager.GetActiveScene()).completed += i => {
    5.             SceneManager.LoadSceneAsync(scene, LoadSceneMode.Additive).completed += j => {
    6.                 SceneManager.SetActiveScene(SceneManager.GetSceneByName(scene));
    7.                 SceneManager.UnloadSceneAsync(temp);
    8.             };
    9.         };
    10.     }
    11.  
     
    Last edited: Aug 2, 2020
    Csharp_jedi likes this.