简体   繁体   中英

Unity 3D shoot and destroy enemy do not work

I have a Player who uses a weapon to shoot and destroy enemies. I have a code for a gun:

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

and the code for bullets:

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

public class Bullet : MonoBehaviour
{

 private void OnTriggerEnter(Collider other)
 {
 if (other.tag == "Enemy")

    {
      Destroy(gameObject);
    }
  }
}

even though my enemy is tagged as 'enemy' and has a box collider triggered it doesnt disappear. The bullet prefab has rigidbody and sphere collider. Please help:)

If you use Destroy(gameObject) you are destroying the bullet.

In order to destroy the enemy you should do a

Destroy(other.gameObject)

So you will destroy the object that actually triggered, the enemy

You are telling the bullet to destroy itself. You probably rather wanted

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM