- Home /
Player not getting destroyed when touched by enemies
Hello! I'm trying to develop my first 2D shooter. I have 3 types of enemies and 3 types of spells which destroys one of the enemies, but if it hits a wrong enemy type just the projectile gets destroyed.
I've been trying to include a destroy script for when the player gets touched by an enemy, but for some reason I can't get it going.
Here is the script for enemy prefab:
using UnityEngine; using System.Collections;
public class Enemy : MonoBehaviour {
public float EnemySpeed;
private Transform myTransform;
void Start () {
myTransform = transform;
}
void Update () {
float amtToMove = EnemySpeed * Time.deltaTime;
myTransform.Translate(Vector3.left * amtToMove);
if (myTransform.position.x < -10.9f)
Destroy(this.gameObject);
}
void OnTriggerEnter(Collider otherObject)
{
if (otherObject.tag == "Wizzard") {
Destroy (otherObject.gameObject);
Destroy (gameObject);
}
}
}
Answer by JazzWolf · Nov 09, 2014 at 07:38 PM
This is the enemy script and you want it to destroy the player? In you're onTriggerEnter script you're checking for the tags "EnemyArcane" "EnemyFire" and "EnemyFrost", but theres no checking for the player. I'm guessing the player doesn't have these tags. I think you need to change those to the players tag and make sure your player has the right tag. like this
EDIT: for 2D colliders your probably want to use the 2D physics variations
void OnTriggerEnter2D(Collider2D otherObject)
{
if (otherObject.tag == "PlayerTag") {
Destroy (otherObject.gameObject);
Destroy (gameObject);
}
}
It might be worth using the OnTriggerEnter and destroy on the player script itself. It seems you're just losing track of your logic a little bit. Let me know if this helps or if you can expand on the problem.
Yeah, sorry I copied the wrong code, the Player has the tag "Wizzard", I just tried to do the other way around, the Player to destroy itself when it gets touched by an enemy but didn't work as well.
Wait a sec.. this is a 2D game correct? You are most likely using BoxCollider2D? I'm not positive it matters, but you may need to use OnTriggerEnter2D(Collider2D otherObject).
Also this is probably done already but just in case make sure you have checked the Is Trigger box on the Collider2D's.
Yes, it is a 2D, but the "Player" is a cube, the "enemies" are capsules and the "projectiles" are spheres. As I said, I managed to get projectiles and enemies work with each other, but using the same settings and different parameters I can't get the capsules interact with the cube, and I made sure the colider area is large enough on the cube. I have is Trigger checked on the enemies.
Answer by RayzaN · Nov 10, 2014 at 04:25 PM
I managed to solve it, apparently the player had to be a prefab as well. Thanks for your help guys! Have a nice day! :)