Sek19
1
what I am trying to do is on touch, that specific gameobject will be destroyed. I have created a tag by the name of “city” and placed the respective objects in this tagging system. So here’s my problem, when I run this script and click on an object they are destroyed not by what was touched but in the order they are listed in the scene. What can I do to change this and make it so when clicking on the specific object, it destroys that object. I am sorry if this is any type of repeat question as I have looked all over the web and this form for answers.
public class touch : MonoBehaviour {
public GameObject Tower;
private Ray ray; // cast array
public RaycastHit rayHitInfo = new RaycastHit(); // object that was hit by array
// Update is called once per frame
void Update () {
if (Input.touches.Length <= 0)
{
//if no touch recognised then there will be no interaction
}
else
{
for (int i = 0; i < Input.touchCount; i++)
{
if(Input.GetTouch(i).phase == TouchPhase.Began)
{
ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position); // creates ray from screen point positoin
if(Physics.Raycast(ray, out rayHitInfo))
{
Tower = GameObject.FindWithTag("city");
Destroy (Tower);
}
}
}
}
}
}
Baste
2
The clicked object is available in the hitInfo object:
if(Physics.Raycast(ray, out rayHitInfo)) {
GameObject hitObject = rayHitInfo.collider.gameObject;
if(hitObject.tag == "city")
Destroy(hitObject);
}
By the way, you don’t have to instantiate the RaycastHit object on the top of your file - since it’s an out parameter, the method guarantees that it will create the object and set it. So you can delete this line:
public RaycastHit rayHitInfo = new RaycastHit();
And instead simply declare it right before the raycast:
ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position); // creates ray from screen point positoin
RaycastHit rayHitInfo; //new line
if(Physics.Raycast(ray, out rayHitInfo))
Your touched object is contained in your rayHitInfo.
Try
if (Physics.Raycast (ray, out rayHitInfo)) {
Destroy (rayHitInfo.transform.gameObject);
}