So, I’m working on a Run Gun game, and I’m trying to attach a script on a enemy to make it detect collisions with the bullets. Since I’m working on unity2D there is a polygon collider on the bullet and a box collider on the enemy, currently this is the code I have:
#pragma strict
var enemyhealth = 2.0;
function Start () {
}
function OnTriggerEnter2D (col : Collider2D){
if (col.tag == ("Bullet")){
Debug.Log("hit");
enemyhealth -= 1;
}
}
function Update () {
if(enemyhealth == 0){
Destroy(gameObject);
}
}
I decided to go with Triggers but I also tested with OnCollisionEnter2D and had no results. It seems that it does not detect the collisions and I have no idea why. Could anyone help me?
Did you add rigidbodies ?
And that is exactly what I forgot to do! Thanks!
And let me just reuse this thread for another question.
I’ve got the following script for my bullet:
#pragma strict
var speed = 20.0;
var timer = 0.0;
function Start () {
}
function OnTriggerEnter2D (col : Collider2D){
if(col.tag == "ground" || col.tag == "Enemy"){
Destroy(gameObject);
}
}
function Update () {
transform.Translate(Vector2.right * speed * Time.deltaTime , Space.Self);
timer += Time.deltaTime;
if(timer > 3.0){
Destroy(gameObject);
}
}
It works well, but when the bullet hits an enemy or the ground it just goes through it for some time before it gets destroyed, anyone got an idea on how to get rid of this delay? because bullets usually don’t pierce through a monster and disappear in mid air like its happening here =/
are the enemies and the ground set to those tags in the inspector?
Yes, initially i thought this was the problem… but it seems to be something else.
How did you set the physics layers ? What you describe is that the collision never actually happens right ?
Another possibility if that wasn’t the answer, is that maybe you move your bullet too fast and it ‘jumps’ behind the colliders thus never triggering the collision… We’ll see to fix it if this is the case but for now check if the collision can happen or not.
Also, add some debug when you develop a script it’ll save you a lot of time figuring out what is going on. And you can remove it when the script works.
Added a debug, and what is happening is that the collision happens, but the destroy takes to long to happen And so the bullet disappears in mid air. I checked and it disappears because of the Destroy(gameObject), nothing related to the timer.
Well, you could disable the gameObject in the meantime. That would happen instantly for sure.