- Home /
destroy ''fireball'' on collision
So i made this code using several codes found in unity questions, the script is attached to a billboard enemy (doom style).... this is the script the bullets seem like soap bubbles and they don't destroy on collisions
using UnityEngine; using System.Collections;
public class S_skullTower : MonoBehaviour {
public Transform target;
public float turretSpeed;
public float fireRate;
public float fireBallHeight;
public GameObject fireBall;
public float range;
float distance;
private float _lastShotTime = float.MinValue;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
//Rotate turret to look at player.
Vector3 relativePos = target.position - transform.position;
Quaternion rotation = Quaternion.LookRotation(relativePos);
rotation.x=0;
rotation.z=0;
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * turretSpeed);
//Fire at player when in range.
distance = Vector3.Distance(transform.position,target.position);
if (distance < range && Time.time > _lastShotTime + (3.0f / fireRate)){
_lastShotTime = Time.time;
launchFireBall();
}
}
void launchFireBall()
{
Vector3 position = new Vector3(transform.position.x, transform.position.y + fireBallHeight, transform.position.z);
Instantiate(fireBall, position, transform.rotation);
Rigidbody rb = fireBall.GetComponent<Rigidbody> ();
rb.velocity = transform.forward * 40;
}
void OnTriggerEnter(Collider fireball)
{
if (fireBall.gameObject.tag == "Player")
{
DestroyObject(fireBall.gameObject);
Debug.Log("Bullet was destroyed");
}
}
}
Answer by zviaz · May 11, 2015 at 07:27 PM
This is the standard way to destroy objects on collision.
C#
using UnityEngine;
using System.Collections;
public class DestroyObject : MonoBehaviour
{
void OnCollisionEnter (Collision col)
{
if(col.gameObject.tag == "Object")
{
Destroy(col.gameObject);
}
}
}
JavaScript
#pragma strict
function OnCollisionEnter (col : Collision)
{
if(col.gameObject.tag == "Object")
{
Destroy(col.gameObject);
}
}
Just set the appropriate tags on the object you want destroyed and remember that one of the objects (in this case your bullets) must have a rigid body component attached.
void OnTriggerEnter(Collider fireball)
{
if (fireball.gameObject.tag == "Player")
{
Destroy(fireball.gameObject);
Debug.Log("Bullet was destroyed");
}
}
You specify void OnTriggerEnter(Collider fireball)
but then reference it as fireBall if (fireBall.gameObject.tag == "Player")
so that might be your problem.
Your answer
Follow this Question
Related Questions
Object not being destroyed when shot 0 Answers
How to make my bullets spread when fired 3 Answers
scripting question 3 Answers
Turret bullet rotation problem 1 Answer
Fast bullet ignor collision sometimes 3 Answers