我制作了3D游戏,并且有一个第一人称控制器,可以通过操纵杆进行控制。我希望播放器仅在我触摸屏幕上的按钮时才射击,但是现在我只要在触摸屏幕上的任何东西时都可以射击。这是拍摄功能的脚本:
using UnityEngine;
using UnityEngine.UI;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public Button button;
// Start is called before the first frame update
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
button.onClick.AddListener(TaskOnClick);
}
// Update is called once per frame
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, forward, Color.green);
}
void Shoot()
{
RaycastHit hit;
if( Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if(target != null)
{
target.TakeDamage(damage);
}
}
}
void OnCollisionEnter(Collision collision)
{
Debug.DrawRay(collision.contacts[0].point, collision.contacts[0].normal, Color.green, 2, false);
}
void TaskOnClick()
{
Shoot();
}
}
答案 0 :(得分:0)
只要您按下“ Fire1”按钮,您的Shoot()
方法就会运行,因为您唯一要做的检查就是(Input.GetButtonDown("Fire1"))
。
如果您要依靠按钮触发,则需要删除部分代码,并在每次单击按钮时调用Shoot()
。
您可以使用代码将事件添加到按钮,如here
所述 public Button m_YourFirstButton;
void Start()
{
//Calls the TaskOnClick/TaskWithParameters/ButtonClicked method when you click the Button
m_YourFirstButton.onClick.AddListener(TaskOnClick);
}
void TaskOnClick()
{
//Output this to console when Button1 or Button3 is clicked
Debug.Log("You have clicked the button!");
}
或者您可以通过检查枪支的单方面行为从检查员处调用它。