在允许级别更改之前满足条件

本文关键字:满足 条件 许级别 | 更新日期: 2023-09-27 18:22:29

我正试图在游戏中添加一枚硬币。如果硬币没有被触摸,那么在玩家触摸硬币之前,关卡将无法切换。我的脚本试图在变量中设置一个值,然后当值增加到1时,它允许级别更改。

如何修复脚本?

硬币脚本:

using UnityEngine;
using System.Collections;
public class Coin : MonoBehaviour {
    public GameObject destroyCoin;
    public static int coinWorth = 0;
    void OnCollisionEnter(Collision other)
    {
        if (other.transform.tag == "Coin")
        {
            Destroy(destroyCoin);
            coinWorth = 1;
        }
    }
}

GameManager脚本:

using UnityEngine;
using System.Collections;
public class GameManager4 : MonoBehaviour {
    Coin coinValue = GetComponent<Coin>().coinWorth;
    void Update ()
    {
        coinValue = Coin.coinWorth;
    }
    void OnCollisionEnter(Collision other){
        if (other.transform.tag == "Complete" && coinValue > 0) {
            Application.LoadLevel(1);
        }
    }
}

在允许级别更改之前满足条件

让硬币在碰撞时直接将其值发送给GameManager可能会更简单。

如果你的硬币可能正在搜索"玩家"标签而不是"硬币"标签(我假设coin.cs脚本将附加到一个带有"硬币"标记的硬币对象上)。

所以在你的脚本中,它看起来是这样的:

using UnityEngine;
using System.Collections;
public class Coin : MonoBehaviour {
    // Drag your Game Manager object into this slot in the inspector
    public GameObject GameManager;
    public static int coinWorth = 1;
    void OnCollisionEnter(Collision other)
    {
        // If the coin is collided into by an object tagged 'player'
        if (other.transform.tag == "Player")
       {
            // retrieve the gamemanager component from the game manager object and increment its value
            GameManager.GetComponent<GameManager4>().coinValue++;
            // Destroy this instance of the coin
            Destroy(gameObject);
       }
    }
}

然后你的第二个脚本

using UnityEngine;
using System.Collections;
public class GameManager4 : MonoBehaviour {
    // Declare the coinValue as a public int so that it can be accessed from the coin script directly
    public int coinValue = 0;
    void Update ()
    {
        // This shouldn't be necessary to check on each update cycle
        //coinValue = Coin.coinWorth;
    }
    void OnCollisionEnter(Collision other){
        if (other.transform.tag == "Complete" && coinValue > 0) {
            Application.LoadLevel(1);
        }
    }
}

当然,如果你从预制件中实例化硬币,那么你需要采取不同的做法,因为你无法在检查员中拖动游戏标记。如果是这样的话,那么为游戏管理器使用singleton类可能是值得的。如果是这样的话,请告诉我,我将向您展示如何做到这一点:)