如何阻止 UI 统一闪烁

时间:2021-07-18 12:17:21

标签: c# unity3d

任何人都知道我如何阻止它闪烁,基本上我正在做一个光线投射,如果它碰到了制作台,它会显示一个文本,说按 e 进行制作,但它正在闪烁,因为它在无效更新功能中,但是如果任何人都知道一个很好的解决方法,谢谢!

if(hit.collider.tag == "CraftingTable")
{
    if(textIsOn)
    {
        noshowcraftingtext();
    }
    else
    {
        showcraftingtext();
    }
}
void showcraftingtext()
{
    textIsOn = true;
    pressEToShowCraftingTableUI.SetActive(true);
}

void noshowcraftingtext()
{
    textIsOn = false;
    pressEToShowCraftingTableUI.SetActive(false);
}

1 个答案:

答案 0 :(得分:0)

你的代码的主要问题是你试图在状态改变后改变状态。

这就是为什么在一个大项目中不是更新的原因,因为所有这些事情都会导致不可预测或逻辑冲突的行为,为了避免这种情况,您应该改用数据驱动的方法。

但要准确解决您的问题,您需要有一个函数,该函数不基于对象的状态,而是返回现在应该发生的情况。

关于你的游戏内部发生的事情并不多,但我猜你是在用鼠标发射光线,然后检查它是否可以制作。

public void Raycaster : MonoBehavior {

 public void YourClickMethod()
 {
   if(hit.collider.tag == "CraftingTable")
     {
       hit.collider.GetComponent<UserInputReceiver>().SetClicked(this);
     }
 }
}

在接收光线投射的对象上,您应该添加:

public class UserInputReceiver : MonoBehavior {
   private bool _isEnabled = false;
   //set this inside inspector
   public GameObject ObjectToEnable;
   private Raycaster _currentSender = null
   public void SetClicked(Raycaster sender){
      _isEnabled = !_isEnabled;
      _currentSender = sender;
   }
   public void Update(){
     if(_currentSender != null && _isEnabled) {
      _isEnabled = Vector3.Distance(transform.position, _currentSender.transform.position) < 1f; //set the threshold based on your unit system
     }
     //or another object, you can put it inside public field and enable him
     //gameObject.SetActive(_isEnabled);
     objectToEnable.SetActive(_isEnabled); //here you can pass a reference through inspector for your canvas

   }
}

这就是您可以通过简短的方式解决这个问题的方法。 此代码将根据接收到的输入和距离设置标志。如果你需要永远保持启用的文本,那么删除距离检查,它只需要第二次点击就可以启用,没有距离依赖。