问题描述
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehavIoUr {
float bulletSpeed = 60;
public GameObject bullet;
void Fire(){
GameObject tempBullet = Instantiate (bullet,transform.position,transform.rotation) as GameObject;
Rigidbody tempRigidBodyBullet = tempBullet.GetComponent<Rigidbody>();
tempRigidBodyBullet.AddForce(tempRigidBodyBullet.transform.forward * bulletSpeed);
Destroy(tempBullet,5f);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Fire();
}
}
}
和子弹代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehavIoUr
{
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Enemy")
{
Destroy(gameObject);
}
}
}
即使我的敌人被标记为“敌人”并且触发了一个盒子碰撞器,它也不会消失。子弹预制件有刚体和球体碰撞器。请帮忙:)
解决方法
如果你使用 Destroy(gameObject) 你就是在摧毁子弹。
为了消灭敌人,你应该做一个
Destroy(other.gameObject)
所以你会摧毁真正触发的物体,敌人
,你是在告诉子弹摧毁自己。你可能更想要
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Enemy"))
{
// Destroy the thing tagged enemy,not youself
Destroy(other.gameObject);
// Could still destroy the bullet itself as well
Destroy (gameObject);
}
}