You need to get an object, or rather its value, and id by clicking on a 2d object. Objects themselves are displayed in a loop when creating a scene, so GameObject.Find does not help, that is, it only displays the value of the first object. Rummaged all that is possible, nothing helps, gives a bunch of errors. The code below does not produce anything, and what is commented out only gives the value of the first object.

public GameObject getItem; private string str; void OnMouseDown(){ str = getItem.GetComponent<sellItem>().value; //str = GameObject.Find("Image(Clone)").GetComponent<sellItem>().value; Debug.Log(str); } 
  • Which mistakes? Why does not work (what is the performance criterion)? It is necessary to put the question correctly! - Valera Kvip
  • If you want to click on GO with the sellItem script, then OnMouseDown should be located in it. - Valera Kvip
  • The performance criterion is the value in the console. But the console is empty. No errors. There is nothing in the sellItem script, empty variable value and id. In unit recently, therefore could not explain something so. I'm trying to write a 2D game, where the working field is a matrix and now I need to track down the click on the cell and get the values ​​of id and value. - Vadim Moroz

1 answer 1

OnMouseDown - Will be called in the following case:

OnMouseDown is a GUIlement or Collider.

In your version like this:

  public class sellItem : MonoBehaviour { int id; string value; void OnMouseDown(){ Debug.Log(id + " " + value); } } 

https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html


As I understand it, you use Image for objects, instead you can use Button . In it you can configure the OnClick event.

Official video on the button: https://www.youtube.com/watch?v=J5ZNuM6K27E


To track click on a cell in the matrix it is not necessary to create a bunch of buttons. You can find the coordinates of the click. https://docs.unity3d.com/ScriptReference/Input-mousePosition.html You also need to consider the cell size and the number of cells (And maybe a number of factors, but depends on the implementation)