0

I know this question has probably been asked many times, but I'm going to ask again.For some reason, my colliders won't work. I have one on my block sprite, and another on my 'miner' sprite. When I hit play, the two start on top of each other. (I'm not sure if this matters, it appears to make no difference.) Each one has a Box Collider 2D. In the script assigned to one of them, it tries to see the collision.

void OnCollisionEnter2D(Collision2D collision)
{
    if (col.gameObject.name == "Miner")
    {
        GameObject.Find("Miner").GetComponent<miner>().block = block;
    }
}

However, this script does not seem to detect the Miner sprite colliding with it. I am certain I am deriving from MonoBehavior, so it's not issue there.

HelpMeGame
  • 57
  • 1
  • 2
  • 12
  • How many `Miner` objects are in your Scene? – derHugo Nov 21 '19 at 06:31
  • 1
    This `if (col.gameObject.name == "Miner") { GameObject.Find("Miner").GetComponent().block = block; }` makes little sense .. if you already have a reference to an object called `Miner` why would you use `Find` (very expensive) to again search for an object with this name? Simply use the one you already got: `col.gameObject.GetComponent().block = block;` – derHugo Nov 21 '19 at 06:33
  • You need to check the collision matrix https://docs.unity3d.com/Manual/CollidersOverview.html – BugFinder Nov 21 '19 at 08:25

2 Answers2

3

Do either of the GameObjects have a RigidBody2D attached to them? At least one GameObject needs to have a RigidBody in any given collision.

  • Ok thanks, can't try this right now, but I am sure neither had a RigidBody attached. I will try that later. – HelpMeGame Nov 21 '19 at 14:56
  • This was the issue! I gave my `Miner` sprite the RigidBody 2D component, and reset his box collider. I believe it was a mix of this and the colliders starting on top of each other, but it works now! – HelpMeGame Nov 21 '19 at 22:58
0

Add some debug statements in your code so that you are sure this method is not running. You should read up here about Collisions in unity. Decide if these objects will be moving and set the appropriate collider. As stated above you will typically need a rigidbody.

Seth Setse
  • 335
  • 3
  • 9