一旦距离足够远,对象的组件就会禁用

问题描述

我正在制作一个无限街机风格的游戏,当玩家开始游戏时,会在地图上随机生成球,玩家的目标是击中它们并获得积分。

无论如何,如果玩家距离足够远,我想禁用碰撞器和精灵以使游戏运行更流畅。或者如果球会自行删除,然后在玩家靠近时重生。

抱歉,这有点令人困惑。此外,如果发生任何变化,球会被实例化。

解决方法

如果你从头开始,你不需要太在意优化,因为我们会在你完成你的游戏之后再做。你需要专注于游戏设计和游戏机制。如果您需要生成对象,您需要了解 Instantiate 方法。你想让球每秒随机产生,你现在需要关于 InvokeReapeating 方法。或者更高级,您将必须了解对象池等等。从头开始学习,不要想复杂。当你完成了基本的,就继续做更大的事情,是的

,

您可以使用 Destroy(GameObject) 清除不再需要的游戏对象。


    Destory(gameObject); // this destroys the game object that the script is attached to

有许多教程可以在各种条件下(例如离开可玩区域)销毁游戏对象。

似乎接近您要寻找的东西的最简单方法是检查球与玩家之间的距离,如果大于阈值,则自毁。这需要通过 Ball 上的脚本来完成,并且您需要对 Player 对象的引用


    const float Threshold = 25f; // Some distance away from the player
    public GameObject Player; // Drop the player on here from the editor,or find using a tag,name,etc.

    void Update()
    {
        // Get the absolute distance between the object and the player
        var distanceToPlayer = Mathf.Abs(Vector3.Distance(transform.position,player.transform.position)); 
        // If greater than threshold,goodbye
        if (distanceToPlayer > Threshold)
        {
            Destroy(gameObject);
        }
    }

现在,如果您想在玩家返回到您的生成管理器可以处理的区域时通过跟踪它生成的对象的状态、事件侦听器等来重新生成对象。