How to continuos firing when user touch (and keep press) a button in Android/iOs?
Using onClick, i can fire only one shot.
Is there an event like "keep-touch" ?
Thanks
How to continuos firing when user touch (and keep press) a button in Android/iOs?
Using onClick, i can fire only one shot.
Is there an event like "keep-touch" ?
Thanks
Check this example on using touch on Mobile devices: https://docs.unity3d.com/Manual/MobileInput.html
Similarly you can use this code to use a boolean variable to start and stop shooting based on touch
// global
bool bContinuousShoot = false;
// In Update loop
for (var touch : Touch in Input.touches) {
if (touch.phase == TouchPhase.Began) {
bContinuousShoot = true;
// You code goes here...
} else if(touch.phase == TouchPhase.Ended) {
bContinuousShoot = false;
}
}
TouchPhase reference: https://docs.unity3d.com/ScriptReference/TouchPhase.html
Supposing you are working with UGUI buttons, you can attach pointer down and pointer up listeners to the buttons. I haven't tested the following code, tell me if you have any problem.
// At the top of your file
using UnityEngine.UI ;
// ...
// Class member
public float fireRate = 0.1f ;
// Drag & Drop the UI button in this field of the inspector
[SerializeField]
private Button shootButton ;
private bool continuousShoot = false ;
private float nextShootTime = 0 ;
private void Awake()
{
if( shootButton == null )
throw new Exception("You haven't assigned a button on the inspector");
EventTrigger eventTrigger = shootButton.AddComponent<EventTrigger>( );
// Pointer down
EventTrigger.Entry pointerDownEntry = new EventTrigger.Entry( );
pointerDownEntry.eventID = EventTriggerType.PointerDown;
pointerDownEntry.callback.AddListener( ( data ) => { EnableContinuousShoot(); } );
eventTrigger.triggers.Add( pointerDownEntry );
// Pointer up
EventTrigger.Entry pointerUpEntry = new EventTrigger.Entry( );
pointerUpEntry.eventID = EventTriggerType.PointerUp;
pointerUpEntry.callback.AddListener( ( data ) => { DisableContinuousShoot() ; } );
eventTrigger.triggers.Add( pointerUpEntry );
}
private void Update()
{
if( continuousShoot && Time.time > nextShootTime )
{
nextShootTime = Time.time + fireRate ;
Shoot() ;
}
}
private void Shoot()
{
// Your code here
}
private void EnableContinuousShoot()
{
continuousShoot = true ;
}
private void DisableContinuousShoot()
{
continuousShoot = false;
}