Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Remove callbacks when destoring gameobject

Discussion in 'Input System' started by Shalafi83, Dec 24, 2021.

  1. Shalafi83

    Shalafi83

    Joined:
    Feb 4, 2018
    Posts:
    18
    Hi,

    i'm using the new input system for my player movement.

    When i destory my player object (e.g. map-change) and later create a new player-gameobject, all input is triggered twice.

    Any idea how to solve this?

    Code (CSharp):
    1. private void OnEnable()
    2.     {
    3.         this.Input = InputManager.Input;
    4.         this.Input.Player.Jump.performed += ctx => this.InputJump();
    5.         this.Input.Player.Movement.performed += ctx => this.InputMovement(ctx.ReadValue<Vector2>());
    6.         this.Input.Player.Movement.canceled += ctx => this.InputMovement(new Vector2(0, 0));
    7.         this.Input.Player.Sprint.performed += ctx => this.InputSprinting(true);
    8.         this.Input.Player.Sprint.canceled += ctx => this.InputSprinting(false);
    9.         this.LastJumpTime = 0;
    10.         this.CurrentState = null;
    11.         this.Jump = false;
    12.     }
    13.  
    14.     private void OnDisable()
    15.     {
    16.         this.Input.Player.Jump.performed -= ctx => this.InputJump();
    17.         this.Input.Player.Movement.performed -= ctx => this.InputMovement(ctx.ReadValue<Vector2>());
    18.         this.Input.Player.Movement.canceled -= ctx => this.InputMovement(new Vector2(0, 0));
    19.         this.Input.Player.Sprint.performed -= ctx => this.InputSprinting(true);
    20.         this.Input.Player.Sprint.canceled -= ctx => this.InputSprinting(false);
    21.         this.Input = null;
    22.     }
    InputManager is a singleton on a DontDestoryOnLoad gameobject
    The old triggers are in an this.gameObject == null...


    Any ideas?
     
  2. BillyWM

    BillyWM

    Joined:
    Dec 29, 2018
    Posts:
    14
    That's not going to work. The callback that you're adding and the one you're removing are different lambdas. They're not the same function, they just happen to have the same code inside them.

    When you type this
    Code (CSharp):
    1. ctx => this.InputJump();
    You're creating a lambda right there, in place. You're creating a lambda once when you add the callback (+=) and you're creating a second, completely different lambda that just happens to do the same thing when you try to remove the callback (-=).

    Create a method instead of a lambda or store a reference to the lambda (a delegate)
     
    Last edited: Dec 27, 2021