如何永久销毁游戏对象?

时间:2020-08-12 23:25:45

标签: c# unity3d

所以,我有这个药水。当游戏中的玩家接触药水时,我想消灭药水。但是,如果玩家死亡,场景将重新加载,并且药水仍将保持水平。如果玩家与魔药相撞,我不希望他们得到它。他们应该只能收集一次药水。

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


public class DestroyPotionForever : MonoBehaviour
{
    public bool potionCollide = false;

    // Start is called before the first frame update
    void Start()
    {
        
    }
    void OnTriggerEnter(){
        if(potionCollide == false){
            Destroy(gameObject);
            bool potionCollide = true;
        }
    }


    // Update is called once per frame
    void Update()
    {
        
    }
}

但是...此代码不起作用。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:3)

一种简单的方法是将您是否已经在PlayerPrefs中拾取了药水。

然后您可以执行以下操作:

void OnTriggerEnter()
{
    if(PlayerPrefs.GetInt("GotPotion", 0) == 0)
    {
        // You didn't get the potion yet, so get it
        Destroy(gameObject);
        PlayerPrefs.SetInt("GotPotion", 1); // got the potion
    }
}

那么,无论您在何处生成药水,都可以:

if(PlayerPrefs.GetInt("GotPotion", 0) == 1)
{
    // Got the potion already, so don't spawn the potion
}

或者,如果您直接将药水放在场景中,则可以这样做:

void Start()
{
    if(PlayerPrefs.GetInt("GotPotion", 0) == 1)
    {
        // If the potion is already picked up, destroy it
        Destroy(gameObject);
    }
}

更好的方法是按照Antnio Pedro Gonalves Ferreira的建议编写自己的保存系统,但这至少可以使您进入演示阶段。

答案 1 :(得分:1)

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


public class DestroyPotionForever : MonoBehaviour
{
    public bool potionCollide = false;

    // Start is called before the first frame update
    void Start()
    {
        
    }
    void OnTriggerEnter(){
        if(potionCollide == false){
            Destroy(gameObject);
            potionCollide = true;
        }
    }


    // Update is called once per frame
    void Update()
    {
        
    }
}

只需使用全局变量。 potionCollide。您创建了局部变量,而不是使用全局变量。

答案 2 :(得分:0)

开始游戏之前,您的药水在现场吗?在运行时发生的任何事情都不会永久改变场景,如果您希望药水永远消失,那么在游戏运行之前它就不会出现在场景的层次结构中。重新加载场景时,它会重置为运行游戏之前的状态。