unity3d 我怎样才能使这个取件代码正常工作?

lb3vh1jj  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(151)

我有这个脚本,我从一个youtube教程。它只是有时在游戏中工作,我不明白为什么。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PickUp : Interactable
{
    public GameObject FlashLightOnPlayer;
    // Start is called before the first frame update
    void Start()
    {
        FlashLightOnPlayer.SetActive(false);
    }
    
    
   private void OnTriggerStay(Collider other) 
   { 
    if (other.gameObject.tag == "Player")
    {
        if(Input.GetKey(KeyCode.E))
        {
        this.gameObject.SetActive(false);
        FlashLightOnPlayer.SetActive(true);
        }
   }
  }
}

这是我拥有的两个对象。Flashlight(1)是Player的子对象。
FlashlightFlashlight(1)
我试着按照这个教程在这里:https://youtu.be/zEfahR66Pa8有时候我试着把它捡起来,它能用,有时候不行。我该怎么办?

4sup72z8

4sup72z81#

https://docs.unity3d.com/ScriptReference/Collider.OnTriggerStay.html开始:
OnTriggerStay是在*几乎所有其他碰撞器的帧上调用的,这个函数是在物理计时器上,所以它不需要运行每一帧。
对于Input.GetKey(),您希望调用Update()中的每一帧,以避免错过任何按键。在OnTriggerStay()等基于物理的对象中调用Input.GetKey()是有风险的,因为OnTriggerStay()运行在独立的物理帧速率上。我尝试查找是否有人在Update()之外使用Input.GetKey(),但到目前为止我还没有找到。您最好的选择是:

  1. Creating a flag in OnTriggerStay() and use Update() to check that flag,或
  2. Creating a flag in Update() and use OnTriggerStay() to check that flag .

相关问题