如何解决功能间计时错误C#、Unity
我有 2 个脚本(runcontrol.cs 和 FireControl.cs)依赖于鼠标点击事件。
runcontrol.cs :由屏幕顶部的按钮触发。点击后,游戏停止。
FireControl.cs :允许角色在点击鼠标时开火。
问题:由于我想停止游戏时必须点击,所以先角色射击,然后游戏停止。我尝试了以下代码进行阻止,但无法阻止。
//runcontroll.cs
private void Start()
{
isRun = true;
}
public void OnButtonClick()
{
if(btn.image.sprite == runsprite)
{
btn.image.sprite = stopSprite;
FindobjectOfType<FireControl>().isRun = false;
isRun = false;
}
else
{
btn.image.sprite = runsprite;
FindobjectOfType<FireControl>().isRun = true;
isRun = true;
}
}
//FireControl.cs
private void Start()
{
isRun = true; //Controlled by runcontrol.cs
}
private void Update()
{
if (isRun)
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
fire = true;
}
else
{
fire = false;
}
}
}
!!! 将 FireControl.cs 更改为 lateupdate 不起作用
解决方法
您正在创建“竞争条件” - 这将首先发生,禁用游戏或触发。跟踪状态并由 OnClick 更新并由 FireControl 读取的单例 GameManager 类在清理代码方面大有帮助,但不会解决竞争条件。
我会看看 this answer 的问题“如何检测鼠标左键单击,但在 UI 按钮组件上发生单击时不检测?”
根据该答案,您可以将 FireControl 更新为在单击按钮时不触发,这样可以避免竞争条件
if (isRun)
{
if (Input.GetKeyDown(KeyCode.Mouse0) && !EventSystem.current.IsPointerOverGameObject())
{
fire = true;
}
else
{
fire = false;
}
}
选项 2 - 使用 RayCast
标记您的按钮以使其可识别,我们将其称为“按钮”。然后做一个 RayCast 并检查指针是否在按钮上,如果是 - 不要开火
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var overButton = false;
if (Physics.Raycast(ray,out var hit)
{
overButton = hit.collider.tag == "button";
}
else
{
overButton = false;
}
// Continue with your fire logic
if (Input.GetKeyDown(KeyCode.Mouse0) && !overButton)
{
// Fire
}
上面有点乱,可以优化,但应该工作
,精灵检查和精灵更改将花费很少的时间,因此玩家首先射击。 Soul:我想你可能会使用 Enumerator() 和 waitforseconds() 来欺骗和改变精灵。
using system;
void Update() {
if(isRun) {
StartCoroutin(myfunction()) ;
}
}
Enumerator myfunction() {
yield return new waitforseconds(0.7f) ;//if you feel 0.7 //seconds is not comfortable then you can change it .
if(isRun) {
if (Input.GetKeyDown(KeyCode.Mouse0))
{
fire = true;
}
else
{
fire = false;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。