- Home /
Destroy an object if it is touched (Android)
Hi!
I'm new working with Unity, and i need to know how i can destroy a cube if i touch over this. For example i need to destroy only the cube B if i touch over this. PD I working with augmmented reality.
I hope that you can help me!
Answer by akisrn · Jun 15, 2017 at 01:58 AM
I created a script with this code and attached it to my Main Camera. It seemed to work.
void Update () {
if (Input.GetMouseButtonDown(0))
{
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Destroy(hit.collider.gameObject);
}
}
}
You can modify it from here to suit your needs. Let me know how it will go.
:D it works! you save me!!!!!
Can you help me with another thing? how i can put score when touch the correct cube? And how i do if i need write the letter that is touched? Apologize me if i abuse, but i'm desesperate!
$$anonymous$$odify your code to something like this.
private int scoreCard;
// Update is called once per frame
void Update () {
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
Ray ray = GetComponent<Camera>().ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Destroy(hit.collider.gameObject);
if (hit.collider.name == "ChangeThisToTheNameOfTheObjectYouWant")
{
Debug.Log(hit.collider.name);
scoreCard++;
}
}
}
}
Just put the scoreCard value in a text or something so the user can see it.