I am shooting a tank shell at a sphere, my tank shell is “Shell Prefab”, my sphere is “Sphere”, both have rigidbodies and colliders attached to them. When I fire by pressing space, the shell goes straight through my sphere, the shell should disappear but doesn’t. Here’s my code:
using UnityEngine;
using System.Collections;
public class DestroyShell : MonoBehaviour {
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.name == "Sphere")
{
Destroy (collision.gameObject);
}
}
}
you might want to look into the way you move your shell. if you’re using transform translate your shell might be ‘teleporting’ through your sphere and thus the collision doesn’t get registered. since you have rigidbody attached, try using Rigidbody.AddForce.
edit :
lol okay i think i missed a point, you want your shell(projectile) AND your sphere(target)to disappear. easy fix :
if(collision.gameObject.name == "Sphere")
{
Destroy (collision.gameObject);
Destroy (this.gameObject);
// you're missing self destruct, thus that's why you only destroy target and not self.
}
oh, and this is done with your DestroyShell script attached to the shell prefab
still doesn’t work, the shells move slower now, and don’t destroy themselves when they hit the sphere. Infact, my code isn’t even being executed at all.
using UnityEngine;
using System.Collections;
public class FireShell : MonoBehaviour {
public float speed;
public Rigidbody proj;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire1"))
{
Rigidbody instantiatedProjectile = Instantiate (proj, transform.position, transform.rotation) as Rigidbody;
instantiatedProjectile.rigidbody.AddForce(0,0, 10*speed);
}
}
}