所以我有一個基本的 2D 游戲,我射擊隨機生成的敵人并殺死他們。我創建了一個腳本,它從螢屏邊緣的兩個點中選擇一個隨機的 x 和 y 值,并在隨機位置實體化我的敵人預制件。這是代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
public Transform LeftScreenIdentifier;
public Transform RightScreenIdentifier;
public GameObject Enemy;
public float spawnEveryXSeconds;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("Spawn",2.0f,spawnEveryXSeconds);
}
// Update is called once per frame
void Update()
{
}
void Spawn()
{
float xPos = Random.Range(LeftScreenIdentifier.position.x,RightScreenIdentifier.position.x);
float yPos = Random.Range(LeftScreenIdentifier.position.y,RightScreenIdentifier.position.y);
Vector2 spawnPos = new Vector2(xPos,yPos);
Instantiate(Enemy,spawnPos,Enemy.transform.rotation);
}
}
我有一個對撞機檢查腳本,如果子彈擊中敵人,它會摧毀它。
void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.CompareTag("Enemy"))
{
Destroy(GameObject.FindGameObjectWithTag("Enemy"));
}
}
這里的問題是,當我向一個敵人射擊時,它有時會摧毀另一個隨機生成的敵人。如何解決這個問題?
謝謝你的時間!
uj5u.com熱心網友回復:
WellFindGameObjectWithTag將找到帶有該標簽的層次結構中的第一個物件。這可以是任何一個。
您寧愿只是想銷毀與您發生碰撞的那個->您已經從引數中獲得了參考
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.CompareTag("Enemy"))
{
Destroy(col.gameObject);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419083.html
標籤:
上一篇:泛型方法引數<T>檢測為變數
下一篇:世界到立方體投影Unity
