Why Isn't My OnCollisionEnter2D Code Not Working?
Hi all,
This is my first question, and I know it's a basic one. I've just started my long and painful journey into the world of programming, and I've encountered an issue where I believe I have the right code, but it's not having the desired effect (it's doing nothing at all).
Game object A (which is poop) is falling, hits Game object B (a cart) which is the player. I want to destroy Object A on collision with B, increment a variable by one, then print to console the variable to ensure its working. However using the below code which I attach to Object B, object A simply hits the cart and sits on top of it without being destroyed.
Object A has a 2d sphere collider which is not a trigger and a non-kinematic rigidbody, I've tried with rigidbody collision option set to discrete and continuous. Object B (player cart) has a non-kinematic rigidbody and 2DBoxColliders which are not triggers.
Help would be much appreciated. :)
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
static int poopHeld; // static variable for how much poop the player cart has currently caught/is holding.
public float speed; // variable for controlling player movement speed.
Rigidbody2D rb2d; // rigidbody2d variable of player.
// Use this for initialization
void Start ()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update ()
{
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal"); //for retrieving player movement left and right.
Vector2 movement = new Vector2(moveHorizontal, 0f); //new vector2 object for player movement
rb2d.AddForce(movement * speed); //player movement calculation
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.name == "Poop") //if statement to detect if other object is the Poop.
{
Destroy(other.gameObject);
poopHeld++;
print(poopHeld);
}
}
}
Answer by Zoogyburger · Feb 08, 2016 at 06:14 PM
Did GameobjectB have 2 2DBoxColliders or just 1 2DBoxColliders? You have to make sure the colliders on both objects are able to hit each other properly to work. All your code worked fine except the last bit:
void OnCollisionEnter2D (Collision2D other){
if (other.gameObject.name == "Poop")
{
Destroy (other.gameObject);
poopHeld++;
Debug.Log("Poop held");
}
}
You should endeavor to tag GameobjectA as "Poop" and change the code to
if (other.gameObject.tag == "Poop")
so that you don't worry about keeping the name the same for instance if you make copy GameobjectA the editor will rename it "Poop1" whick will make your code not work.
Hi Zoogy,
Thanks for your answer. I never did figure out why it wasn't working, but ins$$anonymous$$d set up an additional collider in a different position and set it as a Trigger, then used OnTriggerEnter2D and this seemed to work perfectly.