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

时间:2015-11-18 00:59:43

标签: c# unity3d

我试图在游戏中添加一枚硬币。如果没有触摸硬币,那么该级别将无法切换直到玩家触摸硬币。我的脚本试图在变量中设置一个值,然后当值增加到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);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

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

你的硬币应该是否正在寻找一个“玩家”。标签而不是硬币&#39; tag(我假设Coin.cs脚本将附加到一个硬币对象上,该对象将具有&#39; Coin&#39;标记)。

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

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);
        }
    }
}

当然,如果您使用预制件对硬币进行实例化,那么您需要以不同的方式执行此操作,因为您无法在检查器中拖动游戏操作员。如果是这样,那么为游戏管理器使用单例类可能是值得的。如果是这种情况,请告诉我,我将告诉您如何执行此操作:)