如何解决Unity 3D 射击和摧毁敌人不起作用
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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。