【问题标题】:How do I stop enemies from spawning in Unity 3D?如何阻止敌人在 Unity 3D 中生成?
【发布时间】:2017-01-08 18:48:26
【问题描述】:

我想阻止敌人在其中一个点击“完成”标签时生成。

这是生成敌人的脚本:

public class spawn : MonoBehaviour {

    public GameObject enemy;
    private float spawnpoint;
    public float xlimit = 12f;
    float spawnNewEnemyTimer = 1f;

    void Start()
    {

    }

    public void Update()
    {
        spawnNewEnemyTimer -= Time.deltaTime;

        if (spawnNewEnemyTimer <= 0 )
        {
            spawnNewEnemyTimer = 3;
            GameObject nemico = Instantiate(enemy);
        }
    }

这是使敌人随机出现并移动的脚本:

public class nemici : MonoBehaviour {

    float speed = 4f;

    public GameObject enemy;
    public float xlimit = 12f;
    private float currentPosition;
    public GameObject spawn;
    bool endGame = false;

    void Start()
    {
        if (endGame == false)
        {
            Vector3 newPosition = transform.position;
            newPosition.x = Random.Range(-xlimit, xlimit);
            transform.position = newPosition;
        }
        else if (endGame == true)
        {
            return;
        }
    }

    void Update()
    {
        if (endGame == false)
        {
            //per farlo muovere verso il basso
            Vector3 movimento = new Vector3(0f, -speed, 0f);    //(x, y, z)
            transform.position += movimento * Time.deltaTime;
        }
        else if (endGame == true)
        {
            return;
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.tag == "Player")
        {
            Destroy(enemy);
        }

        else if (other.tag == "Finish")
        {
            Debug.Log("hai perso!");
            endGame = true;
        }
      }
   }

这段代码有什么问题?谢谢!

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    生成新敌人的逻辑在 spawn 类中。决定你是否应该停止生成敌人的逻辑存在于敌人类中。

    只要您希望敌人在击中带有结束标记的对象时停止生成,您就可以成功地将 endgame 布尔值设置为 true。

    void OnTriggerEnter(Collider other){
        if (other.tag == "Finish"){
            Debug.Log("hai perso!");
            endGame = true;
        }
    }
    

    太棒了!但是您实际上并没有使用它来停止生成。 到目前为止,这个变量对每个敌人都是本地的。因此,如果您在 start 和 update 函数中包含检查,它们只会为接触到完成对象的特定敌人激活。这不是你想要的。

    您希望 Spawn 类检查 endgame 变量,如果它处于活动状态,则停止生成敌人。

    为此,您必须能够以某种方式从 Spawn 访问 endgame 变量,我建议您将 endGame 变量设为 Spawn 类的成员。并且您在每个敌人中都包含对 Spawn 的引用。

    总起来可能看起来像这样:

    public class Spawn: MonoBehaviour{
        public boolean endgame = false;
        GameObject nemico = Instantiate(Enemy);
        nemico.ParentSpawn = this
    }
    
    public class Enemy: MonoBehaviour{
        public Spawn spawn;
        void OnTriggerEnter(Collider other){
            if (other.tag == "Finish"){
                Spawn.endGame = true;
            }
        }
    }
    

    然后您可以使用 Spawn 中的残局布尔值来检查您是否应该继续生成敌人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 2017-04-01
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多