Как избежать ссылок на объекты для порожденных объектов в Unity 2D? - PullRequest
0 голосов
/ 29 апреля 2020

В данный момент я программирую игру Unity 2D. Когда игра запущена, машины начинают двигаться и постоянно возрождаются. Я добавил систему жизнеобеспечения, чтобы можно было снимать машины. Моя проблема заключается в том, что моей шкале здоровья, а также моему табло нужны ссылки на объекты, на которые они ссылаются, но я не могу создать ссылку на объект, который не существует до запуска игры. Другая проблема заключается в том, что я не знаю, как добавить холст в сборный дом, чтобы непрерывно создавать его вместе с автомобилями и соединять их с автомобилем. Есть ли способ избежать этих конфликтов или как можно установить ссылки в префабы. Я добавлю код спавнера, машины и табло. Уже заранее спасибо

Spawner:

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

public class Spawner : MonoBehaviour
{
  public GameObject carPrefab;
  public GameObject enemyCarPrefab;
  public GameObject kugel;
  public float respawnTime = 10.0f;
  public int counterPlayer1=0;
  public int counterPlayer2=0;
  public int counterEnergy=0;

  // Use this for initialization
  void Start () {
      StartCoroutine(carWave());
  }
  private void spawnPlayerCars(){
      GameObject a = Instantiate(carPrefab) as GameObject;
      a.transform.position = new Vector2(-855f, -312.9426f);
      counterPlayer1++;
  }
  private void SpawnEnemyCars(){
      GameObject b = Instantiate(enemyCarPrefab) as GameObject;
      b.transform.position = new Vector2(853,-233);
      counterPlayer2++;
  }
  private void SpawnEnergy(){
      GameObject c = Instantiate(kugel) as GameObject;
      c.transform.position = new Vector2(-995,-192);
      counterEnergy++;
  }


  IEnumerator carWave(){
      while(true){
          yield return new WaitForSeconds(respawnTime);
          if(counterPlayer1<3){
          spawnPlayerCars();
          Debug.Log(counterPlayer1);
          }
          if(counterPlayer2<3){
          SpawnEnemyCars();
          Debug.Log(counterPlayer2);
          }
          if(counterEnergy<3){
          SpawnEnergy();
          }
      }
  }


}

Автомобиль:

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

public class EnemyCar : MonoBehaviour
{
    public float speed = 3f;
    int zählerAuto1=0;
    private Vector2 screenBounds;
    public AnzeigePunktzahlPlayer2 points;
    public Spawner sp;
    public int maxHealth=100;
    public int currentHealth;
    public HealthBar healthbar;

    void Start () {
    screenBounds = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height));
    points= GetComponent<AnzeigePunktzahlPlayer2>();
    sp= GetComponent<Spawner>();
    currentHealth=maxHealth;
    healthbar.SetMaxHealth(maxHealth);



    }
    void Update()
    { 
    Vector2 pos = transform.position;
        if(pos.x>-855f){
        pos = transform.position;
        pos.x-= speed* Time.deltaTime;
        transform.position=pos;
        zählerAuto1++;
        }else{
            points.counter++;
            Debug.Log(points.counter);
            sp.counterPlayer2--;
            Debug.Log(sp.counterPlayer2);
            Destroy(this.gameObject);        
        }
    }
    private void OnCollisionEnter2D(Collision2D other) {
        if (other.collider.tag=="Kugel"){
            takeDamage(40);
            //sp.counterPlayer2--;

            if(currentHealth<=0)
            {
            Destroy(this.gameObject);
            }
        }
}
public void takeDamage(int damage){
    currentHealth-= damage;
    healthbar.SetHealth(currentHealth);
}

public void getHealed(int heal){
    currentHealth+= heal;
    healthbar.SetHealth(currentHealth);
}
}

Табло (одна его часть (другая почти такая же)):

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

public class AnzeigePunktzahlPlayer1 : MonoBehaviour
{
    public int counter;
    public TextMeshProUGUI textPlayer1;

    void Start()
    {
 //   counter=0; 
    textPlayer1= GetComponent<TextMeshProUGUI>();
    }

    // Update is called once per frame
    void Update()
    {
        textPlayer1.SetText( counter.ToString());
    }
}



1 Ответ

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

Вы можете сделать заготовки здоровья и холсты детей из сборного автомобиля и сделать так, чтобы они появлялись вместе.

...