Как вывести игрока на сцену проигрыша, когда таймер заканчивается и не убивает достаточно врагов - PullRequest
0 голосов
/ 10 мая 2019

Я создаю игру, в которой игрок должен убить определенное количество врагов, прежде чем истечет таймер.Если игрок не убивает количество врагов, для которых он предназначен, и таймер истекает, он попадает на сцену проигрыша.Моя проблема в том, что даже если таймер истекает и не убивает необходимое количество врагов, его не выводят на сцену проигрыша.Как я могу решить эту проблему?

Сценарий EnemySpawner:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class EnemySpawner : MonoBehaviour {


[SerializeField] GameObject EnemyPreFab;
[SerializeField] int MaxEnemies = 30;
[SerializeField] float EnemySpawnTime = 1.00001f;
[SerializeField] GameObject FirstWaypoint;
int  CurrentNumOfEnemies = 0;
int EnemiesToNextLevel = 7;
int KilledEnemies = 0;
public LevelManager myLevelManager;
public static EnemySpawner Instance = null;
int timesEnemyHit;


IEnumerator SpawningEnemies()
{
    while(CurrentNumOfEnemies <= MaxEnemies)
    {
        GameObject Enemy = Instantiate(EnemyPreFab, this.transform.position, Quaternion.identity);
        CurrentNumOfEnemies++;
        yield return new WaitForSeconds(EnemySpawnTime);
    }
}

void Start()
{
    if (Instance == null)
        Instance = this;
    StartCoroutine(SpawningEnemies());
    timesEnemyHit = 0;
    if (this.gameObject.tag == "EnemyHit")
    {
        CurrentNumOfEnemies++;
    }


}

public void OnEnemyDeath()
{
   /*  CurrentNumOfEnemies--;
     if (CurrentNumOfEnemies < 5)
     {
         // You killed everyone, change scene: 
         LaserLevelManager.LoadLevel("NextLevelMenu");
     }
     */

   /* KilledEnemies++;
    if (KilledEnemies >= EnemiesToNextLevel)
    {
        LaserLevelManager.LoadLevel("NextLevelMenu");
    }
    */

    if(Time.timer == 0.0f && KilledEnemies != EnemiesToNextLevel)
    {
        LaserLevelManager.LoadLevel("Lose");
    }


    }



}

Сценарий таймера:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
 {
public Text TimerText;
public float MainTime;
public static float timer;
public  bool CanCount = true;
public  bool OnlyOnce = false;

void Start()
{
    timer = MainTime; //Timer is gonna be equal to what we set MainTime in the inspector 
}

void Update()
{
    if (timer >= 0.0f && CanCount)
    {
        timer -= Time.deltaTime;//The timer will count down in delta time based on the seconds we have 
        TimerText.text = timer.ToString("F");//Converting Timer into a string value 
    }

    //This means that when the timer reaches zero and OnlyOnce is equal to false 
    else if (timer <= 0.0f && !OnlyOnce) //If the timer goes below 0 and OnlyOnce is not equal to flase 
    {

        CanCount = false; //CanCount is equal to false so we are not counting down anymore since it's not greater than zero and we can't count anymore
        OnlyOnce = true; //This is goning to be done once when it reaches it 
        TimerText.text = "0.00"; //Setting the UI to 0 
        timer = 0.0f; //Setting the timer to 0
    }

    }
}

Ответы [ 2 ]

1 голос
/ 10 мая 2019

С вашей текущей структурой кода: ваш противник может иметь переменные EnemyKilled и EnemiesToNextLevel в качестве открытых переменных. И вы можете использовать переменную Instance EnemySpawner внутри скрипта таймера.

Новый EnemySpawner.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class EnemySpawner : MonoBehaviour {


[SerializeField] GameObject EnemyPreFab;
[SerializeField] int MaxEnemies = 30;
[SerializeField] float EnemySpawnTime = 1.00001f;
[SerializeField] GameObject FirstWaypoint;
int  CurrentNumOfEnemies = 0;
public int EnemiesToNextLevel = 7;
public int KilledEnemies = 0;
public LevelManager myLevelManager;
public static EnemySpawner Instance = null;
int timesEnemyHit;


IEnumerator SpawningEnemies()
{
while(CurrentNumOfEnemies <= MaxEnemies)
{
    GameObject Enemy = Instantiate(EnemyPreFab, this.transform.position, Quaternion.identity);
    CurrentNumOfEnemies++;
    yield return new WaitForSeconds(EnemySpawnTime);
}
}

void Start()
{
if (Instance == null)
    Instance = this;
StartCoroutine(SpawningEnemies());
timesEnemyHit = 0;
if (this.gameObject.tag == "EnemyHit")
{
    CurrentNumOfEnemies++;
}
}

public void OnEnemyDeath()
{
  CurrentNumOfEnemies--;
/*     
if (CurrentNumOfEnemies < 5)
 {
     // You killed everyone, change scene: 
     LaserLevelManager.LoadLevel("NextLevelMenu");
 }
 */
KilledEnemies++;

if (Time.timer > 0 && KilledEnemies >= EnemiesToNextLevel)
{
    LaserLevelManager.LoadLevel("NextLevelMenu");
}   
}
}

Изменен сценарий таймера:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
 {
public Text TimerText;
public float MainTime;
public static float timer;
public  bool CanCount = true;
public  bool OnlyOnce = false;

void Start()
{
timer = MainTime; //Timer is gonna be equal to what we set MainTime in the     inspector 
}

void Update()
{
if (timer >= 0.0f && CanCount)
{
    timer -= Time.deltaTime;//The timer will count down in delta time based on the seconds we have 
    TimerText.text = timer.ToString("F");//Converting Timer into a string value 
}

//This means that when the timer reaches zero and OnlyOnce is equal to false 
else if (timer <= 0.0f && !OnlyOnce) //If the timer goes below 0 and OnlyOnce is not equal to flase 
{

    CanCount = false; //CanCount is equal to false so we are not counting down anymore since it's not greater than zero and we can't count anymore
    OnlyOnce = true; //This is goning to be done once when it reaches it 
    TimerText.text = "0.00"; //Setting the UI to 0 
    timer = 0.0f; //Setting the timer to 0
    if(Time.timer == 0.0f && EnemySpawner.Instance.KilledEnemies != EnemySpawner.Instance.EnemiesToNextLevel)
    {
    LaserLevelManager.LoadLevel("Lose");
    }
        }

    }
}

PS: код может быть улучшен. Дайте мне знать, если это поможет.

0 голосов
/ 10 мая 2019

В функции обновления таймера

void Update()
{
if (timer >= 0.0f && CanCount)
{
    timer -= Time.deltaTime;//The timer will count down in delta time based on the seconds we have 
    TimerText.text = timer.ToString("F");//Converting Timer into a string value 
}

//This means that when the timer reaches zero and OnlyOnce is equal to false 
else if (timer <= 0.0f && !OnlyOnce) //If the timer goes below 0 and OnlyOnce is not equal to flase 
{

    CanCount = false; //CanCount is equal to false so we are not counting down anymore since it's not greater than zero and we can't count anymore
    OnlyOnce = true; //This is goning to be done once when it reaches it 
    TimerText.text = "0.00"; //Setting the UI to 0 
    timer = 0.0f; //Setting the timer to 0
    EnemySpawner.timeIsZero = true;
}

}
}

затем в свой скрипт EnemySpawner добавьте публичный статический логический timeIsZero = false; на вершине, а затем в

public void OnEnemyDeath()
 {
   /*  CurrentNumOfEnemies--;
     if (CurrentNumOfEnemies < 5)
     {
         // You killed everyone, change scene: 
         LaserLevelManager.LoadLevel("NextLevelMenu");
     }
     */

   /* KilledEnemies++;
    if (KilledEnemies >= EnemiesToNextLevel)
    {
        LaserLevelManager.LoadLevel("NextLevelMenu");
    }
    */
if(timeIsZero && KilledEnemies != EnemiesToNextLevel)
{
    LaserLevelManager.LoadLevel("Lose");
}


}



}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...