【问题标题】:How do I add a cooldown to my Unity teleport如何为我的 Unity 传送添加冷却时间
【发布时间】:2022-11-16 16:50:43
【问题描述】:

对于任何混乱的代码,我很抱歉,我对此比较陌生。我在 Unity 中进行了一次有效的传送,但每当我从一个传送器传送到另一个传送器时,我都想做到这一点,以便在您再次使用传送器之前有 5 秒的冷却时间。所以我使用了 IEnumerator,在“justTeleported”再次变为 false 之前添加了 5 秒,但是当我传送时,我立即被传送回来,不得不等待 5 秒才能重试。所以我的想法是,也许我触动扳机的速度太快,在它变成错误之前,这就是我添加两秒的原因。但是现在,每当我进入传送器时,它都会从真到假再到真几次,然后我最终被传送回我来自的地方。如果有人能提供帮助,我将不胜感激。谢谢你。

    {
   public Transform Destination;
    bool justTeleported;
    public GameObject Player = GameObject.FindGameObjectWithTag("Player");
    
  
    // Start is called before the first frame update
    void Start()
    {
        justTeleported = false;
    }

    private void Update()
    {
        print(justTeleported)
    }

    private void OnTriggerEnter2D(Collider2D coll)
    {
        if (coll.gameObject.tag == "Player" && justTeleported == false)
        {
            StartCoroutine("Cooldown");
            

        }
    }

    IEnumerator Cooldown()
    {
        justTeleported = true;
        yield return new WaitForSeconds(2f);
        Player.transform.position = Destination.transform.position;
        yield return new WaitForSecondsRealtime(5f);
        justTeleported = false;
        
    }

【问题讨论】:

  • 我想每个传送点(入口和目的地)都拥有这个脚本?
  • 尝试调用“justTeleported = true;”在“StartCoroutine”之前,当您调用 StartCoroutine 时,您也不需要像字符串一样解析 IEnumerat,因此删除“”字符,最后尝试在 Cooldown() 方法中添加一些“Debug.Log()”,然后在您的触发功能中查看是否一切都符合时序

标签: c# visual-studio unity3d


【解决方案1】:

因为每个传送点都有自己的bool justTeleported,设置第一个为真不会自动将另一个设置为真,所以您需要一些方法来告诉目标传送点脚本启动它自己的冷却协程。这是我的测试脚本,它对我有用。

using System.Collections;
using UnityEngine;

public class Teleport : MonoBehaviour
{
    public Teleport Destination = null;
    public float CooldownTime = 5f;
    private bool justTeleported = false;
    
    public void StartCoolDown()
    {
        StartCoroutine(Cooldown());
    }

    private void OnTriggerEnter2D(Collider2D coll)
    {
        if (coll.gameObject.CompareTag("Player") && !justTeleported) //CompareTag("tag") is better than .tag == "tag"
        {
            TeleportPlayer(coll.gameObject);
        }
    }

    private void TeleportPlayer(GameObject player)
    {
        if (Destination) //if Destination is not null
        {
            StartCoolDown();
            Destination.StartCoolDown(); //tell Destination to cooldown
            player.transform.position = Destination.transform.position;
        }
    }

    private IEnumerator Cooldown()
    {
        justTeleported = true;
        yield return new WaitForSeconds(CooldownTime);
        justTeleported = false;
    }
}

Teleport1(目的地:Teleport2) Teleport2(目的地:Teleport1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2021-10-14
    • 2017-06-18
    相关资源
    最近更新 更多