繁体   English   中英

Unity3d C# 重生

[英]Unity3d C# respawning

如果我在 Unity 中测试我的游戏并重生,我将恢复 3 条生命。 但是当我构建游戏并重生时,我只能恢复 2 条生命。

这是我用于重生的代码(不是完整代码):

public int StarterLives; // 3
public GameObject plr; // My Player
public float maxVoidDist; // -10
public Object respawnLevel; // Level01 (My first and only asset)
public Text LivesHolder; // The text object (UI)

private Vector3 respawnPoint; // This gets updated in Start() and becomes the first position of the player
private string deadLevel; // This gets updated in Start() and becomes the name of my respawnlevel
private int lives; // This gets updated in Start() and becomes StarterLives (3)
private bool delay1 = false;


void Update () {
    if ((plr.transform.position.y <= maxVoidDist) && (delay1.Equals(false)))
    {
        delay1 = true;
        if((lives - 1) <= 0)
        {
            Application.LoadLevel(deadLevel);
            lives = StarterLives + 1;
        } else
        {
            plr.transform.position = respawnPoint;
        }

        lives = lives - 1;
        updateLives();
        delay1 = false;
    }
}

void updateLives()
{
    LivesHolder.text = "Lives: " + lives;
}

完整代码:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GameController : MonoBehaviour {

    public int StarterLives;
    public GameObject plr;
    public float maxVoidDist;
    public Object respawnLevel;
    public Text LivesHolder;

    private Vector3 respawnPoint;
    private string deadLevel;
    private int lives;
    private bool delay1 = false;

    void Awake()
    {
        QualitySettings.vSyncCount = 1;
    }

    // Use this for initialization
    void Start () {
        respawnPoint = plr.transform.position;
        deadLevel = respawnLevel.name;
        lives = StarterLives;
        updateLives();
    }

    // Update is called once per frame
    void Update () {
        if ((plr.transform.position.y <= maxVoidDist) && (delay1.Equals(false)))
        {
            delay1 = true;
            if((lives - 1) <= 0)
            {
                Application.LoadLevel(deadLevel);
                lives = StarterLives + 1;
            } else
            {
                plr.transform.position = respawnPoint;
            }

            lives = lives - 1;
            updateLives();
            delay1 = false;
        }
    }

    void updateLives()
    {
        LivesHolder.text = "Lives: " + lives;
    }
}

我看到一些奇怪的东西,在你的代码中,我希望它们可以代表这个问题:

1)

if((lives - 1) <= 0)

通过此测试,如果您还剩 1 条生命,您将重新开始关卡。 是你想要的吗?

2)

Application.LoadLevel(deadLevel);
lives = StarterLives + 1;

在这个片段中,第二行没有用,因为一旦你调用LoadLevel() ,新场景就会被加载,而你的其余代码不会被执行。 所以, lives = StarterLives + 1; 是死代码。

3)关于第二点,让我们假设这些行的顺序是颠倒的(所以,它们是“正确”的顺序)。 您似乎正在尝试更新某些值,以便在关卡重新启动时拥有它们。 但是我在您的代码中看不到DontDestroyOnLoad ,因此值的保留是无用的。

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM