- Home /
Make a 2D object do something when clicked C#
Hi!
I have read/watch these posts and I still have no idea how to do it because it doesn't work for me.
https://docs.unity3d.com/ScriptReference/RaycastHit2D-collider.html https://www.youtube.com/watch?v=3WL51aHBGmE
The script is like this (the base form, without trying to make it react when it's clicked but when you click anywhere):
public class Dice6_script : MonoBehaviour
{
public GameObject Dice6_1;
public GameObject Dice6_2;
public GameObject Dice6_3;
public GameObject Dice6_4;
public GameObject Dice6_5;
public GameObject Dice6_6;
// Use this for initialization
void Start()
{
Dice6_1.SetActive(false);
Dice6_2.SetActive(false);
Dice6_3.SetActive(false);
Dice6_4.SetActive(false);
Dice6_5.SetActive(false);
Dice6_6.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
int result = Random.Range(1, 7);
if (result == 1)
{
Dice6_1.SetActive(true);
}
else
{
Dice6_1.SetActive(false);
}
if (result == 2)
{
Dice6_2.SetActive(true);
}
else
{
Dice6_2.SetActive(false);
}
if (result == 3)
{
Dice6_3.SetActive(true);
}
else
{
Dice6_3.SetActive(false);
}
if (result == 4)
{
Dice6_4.SetActive(true);
}
else
{
Dice6_4.SetActive(false);
}
if (result == 5)
{
Dice6_5.SetActive(true);
}
else
{
Dice6_5.SetActive(false);
}
if (result == 6)
{
Dice6_6.SetActive(true);
}
else
{
Dice6_6.SetActive(false);
}
}
}
}
I have put on the objects the PollygonCollider, and yet I don't know how to make it. Pls help me
Answer by Kishotta · Jun 26, 2017 at 05:27 PM
You can use OnMouseDown. It gets called on the object you click on.
Also, for all that's good in the world, put those dice in an array or list.
Doesn't work :/, I enabled the Trigger on the Pollygon Collider, and still it doesn't work, it doesn't show any errors, it just doesn't enable the objetcs.
Edit: The problem was that the UI Images don't work well with colliders. On$$anonymous$$ouseDown() doesn't work properly in android, so I recomend using RaycastHit2D.