【问题标题】:Unity 3D shoot and destroy enemy do not workUnity 3D射击和摧毁敌人不起作用
【发布时间】:2021-04-02 09:48:54
【问题描述】:

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

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

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

【问题讨论】:

  • Inspector 中是否对碰撞器进行了触发布尔检查?

标签: c# unity3d 3d game-physics


【解决方案1】:

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

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

【讨论】:

  • Collider other 包含子弹击中的对撞机数据吗?
  • other 是一个标记为IsTriggerCollider,它进入了附加到子弹的碰撞器中是
【解决方案2】:

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

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

Destroy(other.gameObject)

所以你会摧毁真正触发的对象,敌人

【讨论】:

  • 对不起,当我写答案时@derHugo 已经回答了。接受他的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-01
  • 1970-01-01
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多