Unity 3D 射击和摧毁敌人不起作用
Unity 3D shoot and destroy enemy do not work
我有一个使用武器射击和摧毁敌人的玩家。我有一把枪的密码:
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);
}
}
}
即使我的敌人被标记为 'enemy' 并且触发了一个盒子碰撞器,但它并没有消失。子弹预制件有刚体和球体对撞机。请帮助:)
你是在让子弹自行毁灭。你可能更想要
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);
}
}
如果你使用 Destroy(gameObject),你就是在摧毁子弹。
为了消灭敌人你应该做一个
Destroy(other.gameObject)
所以你会摧毁实际触发的对象,敌人
我有一个使用武器射击和摧毁敌人的玩家。我有一把枪的密码:
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);
}
}
}
即使我的敌人被标记为 'enemy' 并且触发了一个盒子碰撞器,但它并没有消失。子弹预制件有刚体和球体对撞机。请帮助:)
你是在让子弹自行毁灭。你可能更想要
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);
}
}
如果你使用 Destroy(gameObject),你就是在摧毁子弹。
为了消灭敌人你应该做一个
Destroy(other.gameObject)
所以你会摧毁实际触发的对象,敌人