Search code examples
unity-game-enginegame-physicsgame-development

Script is working even disabling it in the play mode


Here's the screen recording of the issue: https://youtu.be/WnFuhhiBS7M

There are 2 players. Each have player script on them. That script is responsible for the jump function.

Now when I play the game and press jump button, both players jump as expected. But here's the problem.

When I turn off the script for one of the players and then press jump button, still both players jump. How is this possible?

I'm using the following code to 'find' the button in hierarchy and assign the jump function to the button:

Find Buttons

private void Start() {
        characterColliderTrigger = transform.GetComponentInChildren<BoxCollider2D>();
        characterCollider = transform.GetComponent<BoxCollider2D>();

        GameObject[] movementButtons = GameObject.FindGameObjectsWithTag("MovementButtons");
        foreach (GameObject buttonObject in movementButtons)
        {
            Button button = buttonObject.GetComponent<Button>();
            if (button != null)
            {
                if (button.name == "MoveLeftButton")
                {
                    MoveLeftButton = button;
                }
                else if (button.name == "MoveRightButton")
                {
                    MoveRightButton = button;
                }
                else if (button.name == "JumpButton")
                {
                    JumpButton = button;
                }
            }
        }

        StartCoroutine(AssignButtons());
    }

Assign Button

IEnumerator AssignButtons()
    {
        yield return new WaitForSeconds(0.5f);
    //JUMP BUTTON
        EventTrigger jumpEventTrigger = JumpButton.gameObject.AddComponent<EventTrigger>();
        EventTrigger.Entry jumpPointerDown = new EventTrigger.Entry();
        jumpPointerDown.eventID = EventTriggerType.PointerDown;
        jumpPointerDown.callback.AddListener((data) => { Jump(); });
        jumpEventTrigger.triggers.Add(jumpPointerDown);
    
    }

Jump Function

public void Jump()
    {
        if(canJump && !someoneOnTop)
        {
            rb.velocity = new Vector2(rb.velocity.x,25);
            canJump = false;
        }
    }

Solution

  • This is because you assign a callback to the button. You have at least two ways to correct this:

    • Move the "AssignButtons" call into a void OnEnable() and unassign the callbacks on the void OnDisable() method.
    • Check on the Jump() method if the script is enabled, in your case, just add this.enabled on your conditions.