- Home /
Question by
Imvincible13 · Sep 16, 2020 at 03:49 AM ·
c#2dscripting problemcollision
Why is my collision script not working?
Hi I'm fairly new to unity and coding with C# and I've made a collision detection system. I'm trying to get it to detect whether it touching a certain game object and if its not to destroy itself. Any ideas why its not working?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeleteRoot : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name != "Object1" || collision.gameObject.name != "Object2")
{
Destroy(gameObject);
}
}
}
Comment
Have you tried setting a breakpoint or a Debug.Log() message in OnCollisionEnter2D()? Does it run at all?
Have you attached a RigidBody2D with Body Type = Dynamic to the gameObject in the Inspector?
Answer by b4guw1x · Sep 16, 2020 at 12:03 PM
You can use the collider in istrigger mod and you can use OnTriggerEnter2D(Collider2D collision) function. In this method, you will get the objects that your collider is collided in collision object. For an example :
private void OnTriggerEnter2D(Collider2D collision)
{
if (( collision.CompareTag("enemyBlackCircleTag") || collision.CompareTag("enemySpikeTag") || collision.CompareTag("enemyBlackSquareTag") ) && isAlive == true)
{
animatorState = 1;
//Debug.Log(collision.tag);
if (transform.localScale.x <= 0.30 && collision.CompareTag("enemyBlackCircleTag"))
{
scaleX += 0.03f;
scaleY += 0.03f;
collision.gameObject.SetActive(false);
damageParticle.Play();
audioSource.Play();
}
}
}