Unity 3D 射击和摧毁敌人不起作用

时间:2020-12-23 19:28:49

标签: c# unity3d 3d game-physics

我有一个使用武器射击和摧毁敌人的玩家。我有一把枪的代码:

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);
    }
  }
}

即使我的敌人被标记为“敌人”并且触发了一个盒子碰撞器,它也不会消失。子弹预制件有刚体和球体碰撞器。请帮忙:)

2 个答案:

答案 0 :(得分:4)

如果你使用 Destroy(gameObject) 你就是在摧毁子弹。

为了消灭敌人,你应该做一个

Destroy(other.gameObject)

所以你会摧毁真正触发的物体,敌人

答案 1 :(得分:3)

你是在告诉子弹摧毁自己。你可能更想要

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);
    }
}