Clicked object not reacting appropriately

I am trying to make a game where boxes drop from the sky and you have to click them before they hit, so the boxes go flying away (you have magical powers c: )

Anyways, I am trying to use RaycastHit2D to detect the click on the object. It works fine except for example, let’s say I spawn 2 boxes, box 1 and box 2. I click on box 2, and box 1 goes flying away instead. I don’t know why this is happening, I tried everything.

My script is attached to my player. I use a prefab to instantiate those boxes. My Script for throwing the boxes is below.

using UnityEngine;
using System.Collections;

public class ThrowObjects : MonoBehaviour {

	private void throwObject()
	{
		if(Input.GetButtonDown ("Fire1"))
		{
			RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition),Vector2.zero);
			
			// == null returns false
			// != null returns true
			if(hit != null && hit.collider.tag == "Throwable")
			{
				
				GameObject obj = GameObject.FindWithTag(hit.collider.tag);
				obj.rigidbody2D.gravityScale = -6;
				
				Destroy (obj);
			}
		}
	}
	
	// Use this for initialization
	void Start () 
	{
	}
	
	// Update is called once per frame
	void Update () 
	{
		throwObject ();
	}
}

2 Answers

2

I assume both boxes have the same tag.

Because GameObject.FindWithTag is returning the first GameObject with a tag named ‘Throwable’.

The collider already has a reference to the hit gameobject.

        if(hit != null && hit.collider.tag == "Throwable")
        {
            hit.gameObject.rigidbody2D.gravityScale = -6;
            Destroy(hit.gameObject);
        }

Obviously because your objects share the same tag and you find objects by searching.
Box1 comes first and then Box2.

So if you want to do something to the object you clicked, just use hit.gameObject to do anything you like.