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 ();
}
}