Prevent instantiated objects to get mouse hit
Hi guys! I'm very new in Unity. Sorry for a dumb question.
I'm trying to create a very simple 2d game. Here is a script component of a prefab called "monster" I just create 2 instances of this prefab and trying to detect who is clicked (later I'm going to add hitpoints and subtract them). But I stuck already here in this very simple situation. Problem is that I see that BOTH my monster receive hit. Both of them play the animation "hit".
public class monsterManager : MonoBehaviour { private Animator anim;
void Start () {
anim = GetComponent<Animator>();
}
void Update () {
if (Input.GetButtonDown("Fire1"))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
if (hit)
{
Debug.Log(this.gameObject.name);
anim.SetTrigger("hit");
}
}
}
}
That's my gameManager code where I instantiate my monsters:
public class GameManager : MonoBehaviour {
public static GameManager instance;
[SerializeField]
private GameObject monster;
void Awake()
{
MakeSingleton();
}
void Start()
{
GameObject monster1 = Instantiate(monster, new Vector3(0, 0, 0), Quaternion.identity);
GameObject monster2 = Instantiate(monster, new Vector3(5, 0, 0), Quaternion.identity);
}
void Update()
{
}
void MakeSingleton()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
Monsters are not overlapped! They clearly separated, I'm sure completely. Do I understand correctly that EACH instantiated game object has his OWN script? They are not shared. Are not they? I'm asking because in my situation it looks like a triggering event for all objects when at least one gets the mouse event.