Last active
March 17, 2023 04:51
-
-
Save johnmccole/da07a0e7bc0ca2c6ff5699c9de0114a7 to your computer and use it in GitHub Desktop.
Use a variable to allow the player to perform an action if the button is held. Place the variable in a Coroutine to allow the user to repeat it over. isFiring in this case, it stops the Coroutine when set to false.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.InputSystem; | |
public class Firing : MonoBehaviour | |
{ | |
[Header("Weapons")] | |
public GameObject mainWeapon; | |
public GameObject backupWeapon; | |
private GameObject Player; | |
private PlayerControls playerControls; | |
private PlayerInput playerInput; | |
private bool isFiring; | |
// Start is called before the first frame update | |
void Awake() | |
{ | |
Player = this.gameObject; | |
playerControls = new PlayerControls(); | |
playerInput = GetComponent<PlayerInput>(); | |
} | |
private void OnEnable() | |
{ | |
playerControls.Enable(); | |
playerControls.Player.FireMain.performed += FireMain; | |
playerControls.Player.FireMain.canceled += FireMain; | |
playerControls.Player.FireBackup.performed += FireBackup; | |
playerControls.Player.FireBackup.canceled += FireBackup; | |
} | |
private void OnDisable() | |
{ | |
playerControls.Disable(); | |
playerControls.Player.FireMain.performed -= FireMain; | |
playerControls.Player.FireMain.canceled -= FireMain; | |
playerControls.Player.FireBackup.performed -= FireBackup; | |
playerControls.Player.FireBackup.canceled -= FireBackup; | |
} | |
private void FireMain(InputAction.CallbackContext obj) | |
{ | |
// Button is held down | |
if ( obj.performed ) | |
{ | |
isFiring = true; | |
} | |
// Button is released | |
else | |
{ | |
isFiring = false; | |
} | |
// Run the Coroutine | |
StartCoroutine( loopFireMain() ); | |
} | |
// The Coroutine to run | |
IEnumerator loopFireMain() | |
{ | |
// Check the button is held down, do nothing if it's not | |
if ( isFiring ) | |
{ | |
Ray mainRay = new Ray(Player.transform.position, Player.transform.forward); | |
if ( Physics.Raycast(mainRay, out RaycastHit mainHit, 100f) ) | |
{ | |
// hit code here | |
} | |
yield return new WaitForSeconds(0.2f); | |
StartCoroutine( loopFireMain() ); | |
} | |
} | |
private void FireBackup(InputAction.CallbackContext obj) | |
{ | |
Ray backupRay = new Ray(Player.transform.position, Player.transform.forward); | |
if (Physics.Raycast(backupRay, out RaycastHit backupHit, 100f)) | |
{ | |
// hit code here | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment