Hello, I’m making FPS game and I want clones of the bullet to destroy if they touch terrain. Can you help me with script for that? Thank you.
Hello, its simple. Just tag your Terain with “LEVEL”. And then add C# script:
Time when it collides and destroys itself.
using UnityEngine;
using System.Collections;
public class BulletDestruction : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll)
{
if(coll.gameObject.tag == “LEVEL”)
{
Destroy (this.gameObject, 3);
}
}
}
JAVA:
function Start () {
}
function OnCollisionEnter2D(coll: Collision2D)
{
if (coll.gameObject.tag == “LEVEL”)
{
Destroy(this.gameObject, 2);
}
}
I have named file as “BulletDestruction”, tagged terrain as LEVEL and added C# script to the bullet and it just doesn’t do anything, bullet still exists on the ground but script works fine because there is no errors.
- EDIT
I’m sure code is fine but it just still doesn’t do anything. I’ve tried both ways with js and C#.
Oh, sorry… My bad… You shouldnt use 2D Im curently working on 2d so i forgot about 3d ;DD… Tested it this time, works.
JAVA:
#pragma strict
function OnCollisionEnter(coll : Collision)
{
if(coll.gameObject.tag == “LEVEL”)
{
Destroy (this.gameObject, 3);
}
}
C#:
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
void OnCollisionEnter(Collision coll)
{
if(coll.gameObject.tag == “LEVEL”)
{
Destroy (this.gameObject, 3);
}
}
}
Dont destroy it pool it … it will save the cost of instantiation and destruction
There was an awesome tutorial based on this recently https://www.youtube.com/watch?v=9-zDOJllPZ8
As for the collision with Terrain make sure the terrain has a terrain collider and that “is trigger” is not set
Then on the colliding object make sure it has a collider (sphere for cheapness!) and a rigidbody
This should fire the OnCollisionEnter event on your script
Well, yes. The concept is really simular. But use pool only if youre instantiating a lot of bullets. And when i say a lot i really mean a lot. So with the script that i wrote its simplier and easier, yet its not as good as pooling. It works both.