Unity3d C#respawning

时间:2015-11-17 10:20:16

标签: c# unity3d 3d

如果我在Unity中测试我的游戏并且我重生,我会恢复3生命。 但是当我构建游戏时,我重生了,我只有两个生命回来。

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

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 个答案:

答案 0 :(得分:1)

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

1)

if((lives - 1) <= 0)

通过此测试,如果剩余1个生命,则会重新启动该级别。这是你想要的吗?

2)

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

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

3)关于第二点,让我们假设这些线的顺序是反转的(因此,它们在&#34;右边&#34;顺序)。您似乎正在尝试更新某些值,以便在级别重新启动时使用它们。但是我在代码中看不到DontDestroyOnLoad,所以价值观&#39;保存是没用的。

希望这有帮助!