- Home /
How to destroy a particular clone on touch/mouse?
Hi guys,
I'm really struggling on how to destroy a selected game object clone object using my finger? Here is my code:
private void Start()
{
if(cam == null)
{
cam = Camera.main;
}
Vector3 upperCorner = new Vector3(Screen.width, Screen.height, 0);
Vector3 targetWidth = cam.ScreenToWorldPoint(upperCorner);
float ballWidth = ball.GetComponent<Renderer>().bounds.extents.x;
maxWidth = targetWidth.x - ballWidth;
StartCoroutine(VerticalSpawn());
}
//This is used to randomly fall object from the sky.
IEnumerator VerticalSpawn()
{
while (true)
{
// yield return new WaitForSeconds(0.5f);
//For position
Vector3 spawnPosition = new Vector3(UnityEngine.Random.Range(-maxWidth, maxWidth), transform.position.y, 0.0f);
//For rotation
Quaternion spawnRotation = Quaternion.identity;
ball.name = "Ball(" + i++ + ")";
Instantiate(ball, spawnPosition, spawnRotation);
yield return new WaitForSeconds(UnityEngine.Random.Range(0.5f, 1.0f));
}
}
I've tried so many methods from other posts but it doesn't work? Its a 2D project and for smartphones.
Answer by putlucky · Apr 18, 2017 at 04:39 PM
I'm confused, you haven't shown any code for the destruction of your objects... What have you tried exactly?
Does:
if (Input.GetMouseButtonDown(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
Destroy(hit.collider.gameObject);
print("Destroyed ball at " + Input.mousePosition);
}
}
Not work?
For touch, apparantly you can use the event system.
Step by step process courtesy of BoredMormon on the forum:
Add an EventSystem GameObject
Add a PhysicsRaycaster to your camera
Add a collider to you clickable object
Implement the appropriate event system interfaces on your clickable object.
There's also this thread if you want to give it a stab programmatically:
http://answers.unity3d.com/questions/1126621/best-way-to-detect-touch-on-a-gameobject.html
Tons of info on the EventSystem is also available on Youtube.
Your answer
Follow this Question
Related Questions
Spawned tree not falling 1 Answer
Game Object is Instantiating on same position 2 Answers
Change gameobjects position if it's already used by a different gameobject? 1 Answer
How to using remote Bluetooth button to tap on screen 0 Answers
Why is my Prefab Instantiating when the Scene is Loaded? 2 Answers