- Home /
input.touch effect ever object script is attached to
For the last week ive been trying to make a script where i use the input.touch, to kill the object its attached to, when u press on the smartphone screen. The difference from mousebuttondown is, that i want to have the opportunity to tap and kill more than one enemy at a time. Ive read the physics.raycast2D, multitouch manuel, and seen a lot of answers and youtube video, but nothing has worked..
right now im working with this:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class testInput : MonoBehaviour {
private RaycastHit2D hit;
public int health = 3;
private int speed = 2;
void Update ()
{
//transform.Translate(0,-speed * Time.deltaTime,0);
Touch myTouch = Input.GetTouch(0);
Touch[] myTouches = Input.touches;
for(int i = 0; i < Input.touchCount; i++)
{
hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.touches[i].position), Vector2.zero);
if (Input.touches[i].phase == TouchPhase.Began) {
if(hit.collider.tag == "enemy") {
health = health-1;
}
}
if(health <= 0) {
die();
}
}
}
void die () {
Destroy(hit.transform.gameObject);
}
}
The problem is, that it affects all the objects that the script is attached to, so every object gets -1 in health... I know its probably something with the tag, but i can't really find any other solution. Please help a man in pain.
Answer by edcx · Dec 10, 2016 at 03:56 PM
Yes, that's because you are checking hit objects tag. When ou clicked on one and all them throws ray and get the hit, they will all check wheter it is an enemy or not and they don't care if that enemy is themselves or not. Try this instead
// get the collider which is the object you have touched and wanted to
//destroy. Better save this collider in a variable ,so you don't use
//getcomponent all the time
if (hit.collider == transform.GetComponent<Collider>() )
{
Destroy(hit.transform.gameObject);
}
hope that helps.
I tried replacing if(hit.collider.tag == "enemy") with if (hit.collider == transform.GetComponent() )
but it still doesn't work.
Your answer
Follow this Question
Related Questions
Input.GetTouch SOMETIMES not registering on iOS 0 Answers
iPhone multitouch 0 Answers
Multiple touch iPhone Buttons 0 Answers
iPhone Multitouch Problem 1 Answer