OnMouseOver() with Input.GetMouseButtonDown(0) is being triggered for all instantiated objects from a prefab when I only click on one
Im instantiating from a prefab a series of objects (with canvas renderer, they're ui objects) that have the following script inside. I want a click to trigger only for the particular object i'm clicking on. Instead right now it triggers for all of them. It shows the specific variables of each individual item, but its triggering for all three at the same time. I'm stuck and don't know what else to tweak thanks for your help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class OnClick : MonoBehaviour {
// Use this for initialization
void Start () {
}
void OnMouseOver(){
if(Input.GetMouseButtonDown(0)){
Debug.Log("clicked");
/*
GameObject clickedItem;
clickedItem = gameObject;
if (clickedItem == null) {
Debug.Log ("clickedItem is null");
} else if (clickedItem != null) {
Debug.Log ("clickedItem is not null");
}
GameObject title = clickedItem.transform.GetChild (0).gameObject;
if (title == null) {
Debug.Log ("title is null");
} else if (title != null) {
Debug.Log ("title is not null");
}
//Destroy (title);
Transform transform = title.transform;
Text text1 = transform.GetComponent<Text>();
if (text1 == null) {
Debug.Log ("text1 is null");
} else if (text1 != null) {
Debug.Log ("text1 is not null");
}
Debug.Log ("item text is: " + text1.text);
*/
}
}
// Update is called once per frame
void Update () {
OnMouseOver ();
}
}
Answer by UrielKane · Feb 25, 2018 at 03:31 AM
Hello. I'm not an expert on unity. That being said. As far as i can tell the issue is that you are calling the OnMouseOver from the update. So insted for detecting a single call for OnMouseOver you are getting several ones. Depending on what is exactly what are you trying to achieve i whould suggest using unityevents instead of OnMouseOver from script.
So if you are trying just to detect a hover event for like a few script coroutine call or a component acces like enabling or disabling something, you can just use unityevents and avoid those annoying and dirty things. In fact i have discovered unityevents just a few days ago and i was shock by the flexibility they give. Becouse before i was using them only on UI elements such as buttons or whatever. But now i know they can be used for scripts and you can for example use them on trigger events or that kind of stuff.