I have fish gameObjects that have colliders2D so that I can click and move them. I added fish food with Collider2D's but it was hard for me to click on the fish. After I disabled the fish food collider2D it was easier to click on the fish. Is there an alternative when detecting two gameObjeccts without colliders?

  • \$\begingroup\$ Why don't you simply put the fish food on a different layer, and ignore that layer in your fish-click detection script? Getting rid of colliders seems like the wrong solution to this problem. \$\endgroup\$ – DMGregory Nov 13 '20 at 21:49
  • \$\begingroup\$ I tried Physics2D.IgnoreCollision(algae.GetComponent<CircleCollider2D>(), GetComponent<BoxCollider2D>()); but didn't work and i changed the Physics2D from project settings to ignore the fish food \$\endgroup\$ – MM1Content Nov 13 '20 at 21:53
  • \$\begingroup\$ I'm also using OnMouseDown() for click \$\endgroup\$ – MM1Content Nov 13 '20 at 21:55
  • \$\begingroup\$ Well there's your mistake. \$\endgroup\$ – DMGregory Nov 13 '20 at 21:57
  • \$\begingroup\$ lol OnMouseDown? \$\endgroup\$ – MM1Content Nov 13 '20 at 22:02

Don't use OnMouseDown. Having this in your project forces Unity to cast rays for you in the most generic way, which is often less efficient and less precise than casting them yourself.

Make your own script that can filter to the physics layer you care about.

public class FishClicker : MonoBehaviour {

    public LayerMask whatIsFish;

    public float clickRadius = 0.1f;

    void Update() {

        if (Input.GetMouseButtonDown(0)) {
            var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            var hit = Physics2D.OverlapCircle(mousePos, clickRadius, whatIsFish);

            if (hit != null) {
                var fish = hit.GetComponentInParent<Fish>();

                if (fish != null) { fish.DoClickThing(); }
  • \$\begingroup\$ Thank you so much! Cheers :) \$\endgroup\$ – MM1Content Nov 13 '20 at 22:09
  • \$\begingroup\$ Is there a way to draw the Physic2D.Overlap? So that I can see the radius to fine tune it. \$\endgroup\$ – MM1Content Nov 13 '20 at 22:27
  • \$\begingroup\$ void OnDrawGizmos() { Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); Gizmos.DrawWireSphere(mousePos, clickRadius); } \$\endgroup\$ – DMGregory Nov 13 '20 at 22:54
  • \$\begingroup\$ Awesome Appreciate it \$\endgroup\$ – MM1Content Nov 13 '20 at 23:19
  • \$\begingroup\$ At the moment I have seven different colored kind of fish. For instance every time a blue fish is instantiated it has the blue fish script. Your code is moving multiple blue fish at the same time lol so does that mean each colored fish prefab needs its own script? \$\endgroup\$ – MM1Content Nov 13 '20 at 23:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.