Add only one Raycast/Linecast hit to a list
I have made this script so that with the mouse I can "select" the Spriterenderer of these gameobjects I call "molecules" and change them. To select them and unselect them I add them and remove them from a list. I need to use a Linecast because the idea is that even if I don't click exactly on them, but I have the mouse in their vicinity I can select them.
NOTE: I am using some Linq
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class CursorXhair : MonoBehaviour
{
public Sprite newSprite;
public Sprite originalSprite;
List<SpriteRenderer> collidingObjects = new List<SpriteRenderer>();
void Update()
{
Vector2 playerPos = Player.transform.position;
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = mousePos - playerPos;
transform.position = mousePos;
Debug.DrawRay(playerPos, direction);
var hitObjects = Physics2D.Linecast(mousePos, playerPos);
if (hitObjects.collider != null && hitObjects.collider.tag == "Int_Molecule")
{
Debug.Log("hitObjects is colliding");
hitObjects.collider.GetComponent<SpriteRenderer>().sprite = newSprite;
collidingObjects.Add(hitObjects.collider.GetComponent<SpriteRenderer>());
}
else if (collidingObjects.Count >= 1 && hitObjects.collider.tag == "Player")
{
Debug.Log("hitObjects is not colliding");
collidingObjects.Last().GetComponent<SpriteRenderer>().sprite = originalSprite;
collidingObjects.RemoveAt(collidingObjects.Count - 1);
}
}
}
It works well, however I want only one molecule to be selected at a time. This seems not possible because the first if condition keeps being satisfied in these example:
As I am struggling for a solution I thought that maybe I need a way to distinguish the first and second hit molecules, so that only one is returned and changed, but how?
I was thinking, some possibilities:
Return only the first object hit (does this option even makes sense?)
Work out the distance from the mouse and pick only the closer one
Create a mirror list of no longer colliding objects
However I am not sure how I could make neither of this possibilities realities in code. Any suggestions?