The question is answered, apparently, you need '2d' after 'OnCollisionEnter' and 'collision' in order for it to work in 2d. Who would've thought.
C# OnCollisionEnter not Triggering If Statement
So, I'm using a game object with a box collider 2d for a bullet. The script below is supposed to say that if the bullet object collides with the enemy the script is attached to, then it's health is subtracted by 1, the bullet object is destroyed, and a debug message is displayed. This doesn't happen, and instead the bullet pushes the enemy and continues on it's merry way. The script for the bullet literally just says to be moving up at the angle in instantiates at, in case you wanted to know. So, why isn't the bullet corresponding to any of this script?
using UnityEngine;
using System.Collections;
public class EnemyHealthAndDamage : MonoBehaviour
{
public float Health = 3f;
public float maxHealth = 3f;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Health > maxHealth)
{
Health = maxHealth;
}
if (Health <= 0)
{
Destroy(gameObject);
}
}
void OncollisionEnter(Collider other)
{
if (other.gameObject.name == "PlayerBullet(Clone)")
{
Destroy(other.gameObject);
Health = Health - 1;
Debug.Log("Hey it worked");
}
}
}
Answer by tanoshimi · Feb 28, 2016 at 09:46 AM
OnCollisionEnter
not OncollisionEnter
.
This didn't work. Thanks for the correction on that though. I wonder if the script has to be on the bullet object and not the enemy to work?
Follow this Question
Related Questions
Why Isn't My OnCollisionEnter2D Code Not Working? 1 Answer
distinguish players for collision between them 0 Answers
It seems my tag detection does not work properly 2 Answers
Help with collisions not working for no apparent reason?? 0 Answers
destructible tilemap, destroying tiles through overlapcircle 1 Answer