Search Unity

Question Enable/Disable Input

Discussion in 'Input System' started by LevRaskolnikov, Mar 10, 2023.

  1. LevRaskolnikov

    LevRaskolnikov

    Joined:
    Dec 7, 2022
    Posts:
    13
    Hi all

    I'm trying to figure out how to enable and disable the input system temporarily. I want to future-proof avoiding players potentially spamming an input that interrupts a coroutine that causes a glitch that makes it so that coroutine stops running. I think I have most of it figured out, but I don't think I'm using the right language or I'm doing something wrong. Any help would be appreciated.
    It's also been a while since I've embedded code in the Unity forums so I hope I do this right.

    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.InputSystem;
    6.  
    7. public class ADSMakarov : MonoBehaviour
    8. {
    9.  
    10.     public GameObject Gun;
    11.     public GameObject ADSGun;
    12.     public static bool isAiming = false;
    13.     public PlayerInput input = new PlayerInput();
    14.  
    15.     // Start is called before the first frame update
    16.     void Start()
    17.     {
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     void Update()
    22.     {
    23.         if(Input.GetMouseButtonDown(1))
    24.         {
    25.             isAiming = true;
    26.             StartCoroutine(ADSPistol());
    27.             Gun.GetComponent<Animation>().Play("MakarovADS");
    28.         }
    29.  
    30.         if(Input.GetMouseButtonUp(1))
    31.         {
    32.             isAiming = false;
    33.             StartCoroutine(ADSPistol2());
    34.         }
    35.     }
    36.  
    37.     IEnumerator ADSPistol()
    38.     {
    39.         yield return new WaitForSeconds(.3f);
    40.         ADSGun.SetActive(true);
    41.         Gun.SetActive(false);
    42.     }
    43.  
    44.     IEnumerator ADSPistol2()
    45.     {
    46.             input.disable();
    47.             yield return new WaitForSeconds (.75f);
    48.             Gun.SetActive(true);
    49.             Gun.GetComponent<Animation>().Play("MakarovADS2");
    50.             StopCoroutine(ADSPistol());
    51.             ADSGun.SetActive(false);
    52.             input.enable();
    53.     }
    54. }
    55.