Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How to do action when a button pressed with new input system

Discussion in '2D' started by unity_QWGNV3DQKtJFDw, Jun 12, 2020.

  1. unity_QWGNV3DQKtJFDw

    unity_QWGNV3DQKtJFDw

    Joined:
    Jun 6, 2020
    Posts:
    7
    I've been using the new input system recently and I want to make an action happen repeatedly when I hold down a button, but I don't know how and I haven't found much looking on google

    I've created this script but works only with keyboard button and not with gamepad button (r1 and l1) cuz those button change the state 2 time when pressed and again 2 time when relased

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Weapon : MonoBehaviour
    6. {
    7.     public Transform firePoint;
    8.  
    9.     public GameObject bulletPrefab;
    10.  
    11.     InputMaster newInput;
    12.  
    13.     bool IsShooting = false;
    14.  
    15.     private void Awake()
    16.     {
    17.         newInput = new InputMaster();
    18.         newInput.Player.Shoot.performed += ctx => Shoot();
    19.     }
    20.  
    21.     private void OnEnable()
    22.     {
    23.         newInput.Player.Enable();
    24.     }
    25.  
    26.     void Shoot()
    27.     {
    28.         IsShooting = !IsShooting;
    29.         Debug.Log("shot");
    30.     }
    31.  
    32.     private void OnDisable()
    33.     {
    34.         newInput.Player.Disable();
    35.     }
    36.  
    37.     private void FixedUpdate()
    38.     {
    39.         if(IsShooting)
    40.         {
    41.             //shooting logic
    42.             Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
    43.            
    44.         }
    45.     }
    46. }