[英]Trying to destroy the object collided with bullet in Unity 2D
所以我有一個基本的 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"));
}
}
這里的問題是,當我向一個敵人射擊時,它有時會摧毀另一個隨機生成的敵人。 如何解決這個問題?
謝謝你的時間!
那么FindGameObjectWithTag
將找到帶有該標簽的層次結構中的第一個 object 。 這可以是任何一個。
您寧願只是想銷毀與您發生碰撞的那個->您已經從參數中獲得了引用
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.CompareTag("Enemy"))
{
Destroy(col.gameObject);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.