OnTriggerEnter2D not working, tried usual solutions
Hi!
I am working on a melee combat system. So far I have a weapon object that becomes active on a button press and has a Collider2D. In my "training dummy" script I have the following:
using UnityEngine;
using System.Collections;
public class Dummy : MonoBehaviour {
public float health = 100f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
if (health <= 0)
{
KillThis();
}
}
void OnTriggerEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "AttackBox")
{
health -= 25.0f;
}
}
void KillThis()
{
Destroy(this.gameObject);
}
}
The weapon appears in the Player layer, while the dummy is in the Enemy layer. I have checked in the physics settings that the two can collide. I have checked the spelling on the weapon's tag, checked for typos anywhere it may be relevant, The training dummy has a rigidBody using the default settings (however gravity is set to 0 in the dummy's inspector)
In case my weapon code is relevant, here it is.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Weapon : MonoBehaviour {
Vector3 sensorPosition;
//public GameObject Player;
public GameObject player;
private static bool faceRight;
public bool attack;
private HashSet<string> ignoreTags;
// Use this for initialization
void Start () {
gameObject.SetActive(false);
attack = Player.attack;
ignoreTags.Add("BlockSensor");
}
// Update is called once per frame
void Update () {
if (player.tag == "PlayerOne")
{
faceRight = Player.isFacingRight;
if (!faceRight)
{
sensorPosition = new Vector3(player.transform.position.x - 0.5f, player.transform.position.y + 0.01f, player.transform.position.z);
this.transform.position = sensorPosition;
}
else if (faceRight)
{
sensorPosition = new Vector3(player.transform.position.x + 0.5f, player.transform.position.y + 0.01f, player.transform.position.z);
this.transform.position = sensorPosition;
}
}
}
void OnTriggerEnter2D(Collider2D collision)
{
}
}
Hopefully I'm just missing something stupid and this will be easy to fix. Basically when the collision occurs, the dummy should take 25 damage until it reaches zero, and then be destroyed. Any help at all will be appreciated!
Thank you.
Answer by Salmjak · Aug 02, 2016 at 08:41 PM
@ScarcticCG OnTriggerEnter2D takes a Collider2D not a Collision2D which is used in OnCollisionEnter2D. This is the usual solution to this problem (or rather, the usual cause to the problem). Row 21 in the first script.
Your answer
![](https://koobas.hobune.stream/wayback/20220612090028im_/https://answers.unity.com/themes/thub/images/avi.jpg)