Как исправить панель здоровья - PullRequest
0 голосов
/ 28 апреля 2019

Я занимаюсь созданием 2D-игры «Разрушитель блоков» и пытаюсь создать планку здоровья (с 3 звездами).Жизнь пользователя должна уменьшаться всякий раз, когда мяч попадает в коллайдер, однако, когда мяч попадает в невидимый коллайдер, он автоматически попадает на сцену «Потерять».Я пытаюсь вызвать переменную «здоровье» из другого сценария, но она не работает.Я знаю, что делаю что-то не так, но не могу понять, что это такое.Любые предложения?

На изображении ниже представлен инспектор LivesStars1, LivesStars2, LivesStars3 The Inspector of LivesStars1, LivesStars2, LivesStars3

Сценарий работоспособности:

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


public class Health : MonoBehaviour {


public GameObject LivesStars1, LivesStars2, LivesStars3;
public static int health;

void Start()
{
    health = 3;
    LivesStars1.gameObject.SetActive(true); //The object LiveStars1 is being enabled
    LivesStars2.gameObject.SetActive(true); //The object LiveStars2 is being enabled
    LivesStars3.gameObject.SetActive(true); //The object LiveStars3 is being enabled

}

void Update()
{
    int health = health;

    switch (health)
    {
        case 3: //If the user doesn't lose a life all 3 lives remain
            LivesStars1.gameObject.SetActive(true); //The object LiveStars1 is being enabled
            LivesStars2.gameObject.SetActive(true); //The object LiveStars2 is being enabled
            LivesStars3.gameObject.SetActive(true); //The object LiveStars3 is being enabled
            break;
        case 2: //If the user loses one life only LivesStars3 is disabled
            LivesStars1.gameObject.SetActive(true);
            LivesStars2.gameObject.SetActive(true);
            LivesStars3.gameObject.SetActive(false);
            break;
        case 1: //If the user loses two lives then LivesStars2 will also be disabled
            LivesStars1.gameObject.SetActive(true);
            LivesStars2.gameObject.SetActive(false);
            LivesStars3.gameObject.SetActive(false);
            break;
        case 0: //If the uses loses all his lives then the Lose scene is enabled
            LivesStars1.gameObject.SetActive(false);
            LivesStars2.gameObject.SetActive(false);
            LivesStars3.gameObject.SetActive(false);
            break;

    }
  }
}

Скрипт LoadScene:

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

public class LoadScenes : MonoBehaviour {

public LevelManager lvlManager;

//If the ball hits one of the walls the colliders will be triggered
void OnTriggerEnter2D()
{
    print("The wall is triggered by the ball");
    lvlManager.LoadLevel("Lose");
    Bricks.brickCount = 0;

    if(Health.health == 0)
    {
       lvlManager.LoadLevel("Lose");
    }
}



void OnCollisionEnter2D()
{
    Debug.Log("The ball has collided with the wall");
 }

}

Ответы [ 2 ]

0 голосов
/ 29 апреля 2019

Проблема, кажется, в сценарии "LoadScenes" Когда что-то входит в триггер, вызывается OnTriggerEnter2D. Прежде чем проверять, является ли ваше здоровье равным 0, вы уже переходите на свой уровень "Lose".

Это ваш оригинальный код (я добавил комментарий к строке, вызывающей такое поведение)

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

public class LoadScenes : MonoBehaviour {

public LevelManager lvlManager;

//If the ball hits one of the walls the colliders will be triggered
void OnTriggerEnter2D()
{
    print("The wall is triggered by the ball");
    lvlManager.LoadLevel("Lose"); // <-- This here is your problem
    Bricks.brickCount = 0;

    if(Health.health == 0)
    {
       lvlManager.LoadLevel("Lose");
    }
}



void OnCollisionEnter2D()
{
    Debug.Log("The ball has collided with the wall");
 }

}

И вот что должно быть:

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

public class LoadScenes : MonoBehaviour {

public LevelManager lvlManager;

//If the ball hits one of the walls the colliders will be triggered
void OnTriggerEnter2D()
{
    print("The wall is triggered by the ball");

    Bricks.brickCount = 0;

    if(Health.health == 0)
    {
       lvlManager.LoadLevel("Lose");
    }
}



void OnCollisionEnter2D()
{
    Debug.Log("The ball has collided with the wall");
 }

}

TLDR: У вас есть лишнее и ненужное lvlManager.LoadLevel("Lose"); перед проверкой здоровья игрока.

0 голосов
/ 28 апреля 2019

Это не решение, которое вы ищете, но я вижу, что вы постоянно повторяете себя в коде.

Измените switch на это: Если код кажется вам волшебным. Напишите мне

switch (health)
    {
        case 0: //If the uses loses all his lives then the Lose scene is enabled
            SetLivesStarsCondition(true, true, true);
            break;

        case 1: //If the user loses two lives then LivesStars2 will also be disabled
            SetLivesStarsCondition(true, true, false);
            break;

        case 2: //If the user loses one life only LivesStars3 is disabled
            SetLivesStarsCondition(true, false, false);
            break;

        case 3: //If the user doesn't lose a life all 3 lives remain
            SetLivesStarsCondition(false, false, false);
            break;
    }

private void SetLivesStarsCondition(bool starOne, bool starTwo, bool starThree)
{
    LivesStars1.gameObject.SetActive(starOne);
    LivesStars2.gameObject.SetActive(startwo);
    LivesStars3.gameObject.SetActive(starThree);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...