【问题标题】:Meeting a condition before allowing level to change在允许级别更改之前满足条件
【发布时间】:2015-11-19 02:24:01
【问题描述】:

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

【问题讨论】:

  • 如果有人对我的问题有任何疑问,请随时提问

标签: c# unity3d


【解决方案1】:

在碰撞时让 Coin 将其值直接发送到 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);
        }
    }
}

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

【讨论】:

  • 它不允许我将脚本拖到游戏对象中
  • 我刚刚阅读了您所说的内容,我不知道该怎么做。如果您能帮助我,将不胜感激!
  • 当然,所以你有一个带有硬币脚本的硬币对象。然后你有一个游戏管理器对象,上面有游戏管理器脚本。如果您查看硬币对象的检查器,将会有一个名为 Game Manager 的空间。这个空间是您从场景层次结构中拖放游戏管理器对象的地方。用我给你的脚本试试(不是你的角色需要被标记为“玩家”,硬币上需要有一个对撞机。试试这个,让我知道它是怎么回事:)
  • 两个脚本都已经放在播放器上了。我该怎么办?
  • 太好了,我很高兴你能成功 :) 如果你还有其他问题,请随时发布,我会尽力帮助你,祝你好运!
猜你喜欢
  • 2019-11-11
  • 2021-11-14
  • 1970-01-01
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多