- Home /
Problem with holding down UI button to instantiate prefab.
I have a button in my UI that has the following script attached to it.
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class LaserControl : MonoBehaviour,IEventSystemHandler {
public GameObject character;
bool buttonHeld = false;
public GameObject laser;
public float laserSpeed;
public AudioClip laserShot;
public float firingSpeed;
public void pressed (BaseEventData eventData)
{
buttonHeld = true;
}
public void notpressed(BaseEventData eventData)
{
buttonHeld = false;
}
void Start ()
{
character = GameObject.FindWithTag ("Player");
}
void Update(){
if (buttonHeld){
Debug.Log ("click");
InvokeRepeating ("shootLaser", 0.001f, firingSpeed);
}
else{
Debug.Log ("not click");
CancelInvoke("shootLaser");
}
}
void shootLaser() {
GameObject shot = Instantiate (laser, character.transform.position,Quaternion.identity) as GameObject;
shot.GetComponent<Rigidbody2D>().velocity = new Vector2 (0f, laserSpeed);
AudioSource.PlayClipAtPoint (laserShot,transform.position);
}
}
The issue I am having is that I am trying to instantiate at a given interval when the button is held. When I push the button right now, I am invoking at a massive rate. I had the same code being initialized Input.GetKey(KeyCode.space) and the timing was perfect. But when I introduce events, it stops working correctly, and goes into overdrive.
This is my first time using the IEventSysemHandler. I am using Pointer Down and Pointer Up as my BaseEventData at Runtime only.
Any help would be great! I am at a loss where to go from here.
Answer by allenallenallen · Aug 15, 2015 at 03:48 AM
InvokeRepeating ("shootLaser", 0.001f, firingSpeed);
^That means you're repeatedly calling shootLaser() at fireSpeed. Whatever you declared in the inspector.
But if that's set up all correctly, then it's due to the eventData. Why not use EventTrigger?
https://unity3d.com/learn/tutorials/modules/beginner/ui/ui-events-and-event-triggers
Your answer
Follow this Question
Related Questions
BaseEvent Data Not Working for IOS 0 Answers
Can't find EventSystemEditor in Unity 5.1.2f1 1 Answer
Send Mouse Event 0 Answers
Change properties of a button by pressing another button in Unity 1 Answer