2016-04-29 5 views
1

Я довольно новичок в Unity, и у меня были проблемы с подобными проблемами, но я сосала передачу его в свою программу.Обновление количества оставшихся врагов - Unity

Во всяком случае, у меня в основном есть класс Scoring, который будет отслеживать, сколько противников есть на уровне. Я хочу передать это значение в другой класс под названием Bullet_explosive. В этом классе он удалит один из этого числа, когда противник был поражен пулей. После того, как он удалил один из общего числа, я хочу, чтобы это значение было передано обратно в Scoring, чтобы оно отображалось на экране игроку.

Наверное, ответили миллион раз, но мне надоело не знать, как реализовать его в моей собственной программе.

Заранее спасибо.

Вот Scoring класса:

public class Scoring : MonoBehaviour { 

// Create gameobject to store the text object within 
public GameObject textObject; 

// Holds the text displayed on screen 
Text actualText; 

// Holds the remaining number of enemies 
public static int enemiesRemaining = 12; 



// Use this for initialization 
void Start() 
{ 
    // Stores the gameobject called EnemiesRemaining 
    textObject = GameObject.Find ("EnemiesRemaining"); 
    // Gets the text component of that gameobject 
    actualText = textObject.GetComponent<Text>(); 
    // Stores what text the display will actually show 
    actualText.text = "Enemies Remaining: " + enemiesRemaining; 
} 



// Update is called once per frame 
void Update() 
{ 
    // Updates the display 
    actualText.text = "Enemies Remaining: " + enemiesRemaining; 
} 

Вот Bullet_explosive класса:

public class Bullet_explosive : MonoBehaviour { 

// Lifespan of the bullet 
float lifespan = 1.5f; 

// Setting up game objects 
public GameObject fireEffect; 
public GameObject explosion; 
public GameObject theGate; 

//Passing through the enemies remaining 
private static int score; 


// Use this for initialization 
void Start() 
{ 
} 

// Update is called once per frame 
void Update() 
{ 

    score = Scoring.enemiesRemaining; 


    lifespan -= Time.deltaTime; 

    // Once the lifespan reaches 0, bullet is destroyed 
    if (lifespan <= 0) 
    { 
     Explode(); 
    } 
} 

void OnCollisionEnter(Collision collision) 
{ 
    if (collision.gameObject.tag == "Enemy") 
    { 
     // Reduces the remaining enemies 
     score -= 1; 

     // Checks for no remaining enemies 
     if (score <= 0) 
     { 
      // Removes the gate 
      Destroy(GameObject.FindWithTag ("Gate")); 
     } 

     // Changes the tag of the target hit 
     collision.gameObject.tag = "Untagged"; 

     // Applies visual effects at the position and rotation of the target 
     Instantiate (fireEffect, collision.transform.position, Quaternion.identity); 
     Instantiate (explosion, collision.transform.position, Quaternion.identity); 

     // Removes bullet and target 
     Explode(); 
     Destroy (collision.gameObject); 

    } 
} 

void Explode() 
{ 
    Destroy (gameObject); 
} 

ответ

3

Я считаю, что это слишком много усилий, чтобы иметь два static поля, которые означают одно и то же. Вы должны сделать только одно поле для этого и всегда ссылаться на это же поле в классе Scoring.

public class Bullet_explosive : MonoBehaviour { 

// Lifespan of the bullet 
float lifespan = 1.5f; 

// Setting up game objects 
public GameObject fireEffect; 
public GameObject explosion; 
public GameObject theGate; 


// Use this for initialization 
void Start() { } 

// Update is called once per frame 
void Update() 
{ 
    /* no "score" updating needed here in Update() */  
    lifespan -= Time.deltaTime; 

    // Once the lifespan reaches 0, bullet is destroyed 
    if (lifespan <= 0) 
    { 
     Explode(); 
    } 
} 

void OnCollisionEnter(Collision collision) 
{ 
    if (collision.gameObject.tag == "Enemy") 
    { 
     // Reduces the remaining enemies 
     //Directly modify that one static field 
     Scoring.enemiesRemaining -= 1; 

     // Checks for no remaining enemies 
     if (Scoring.enemiesRemaining <= 0) //here too 
     { 
      // Removes the gate 
      Destroy(GameObject.FindWithTag ("Gate")); 
     } 

     // Changes the tag of the target hit 
     collision.gameObject.tag = "Untagged"; 

     // Applies visual effects at the position and rotation of the target 
     Instantiate (fireEffect, collision.transform.position, Quaternion.identity); 
     Instantiate (explosion, collision.transform.position, Quaternion.identity); 

     // Removes bullet and target 
     Explode(); 
     Destroy (collision.gameObject); 
    } 
} 

void Explode() 
{ 
    Destroy (gameObject); 
} 

И это должно быть так.

+0

Также я бы рекомендовал только обновлять текстовое поле, когда значение действительно изменяется. Для этого вам понадобится либо функция для установки оценки, либо обновление текста, либо свойство, которое делает то же самое. Это также инкапсулирует вашу оценку. –

+0

В классе 'Scoring' у вас есть метод' Update() ', который уже выглядит хорошо и должен постоянно обновлять значение' enemyRemaining'. Поэтому он всегда должен быть актуальным. Вы уверены, что сейчас изменяете «Scoring.enemiesRemaining»? Поэтому он должен быть надлежащим образом включен в этот «Текст». Поместите некоторые вызовы в 'Update()', чтобы увидеть, как он выполняется. У вас есть этот скрипт, созданный на каком-то объекте, не так ли? –

Смежные вопросы