- Home /
Logic problem with RaycastHit and prefabs scripts
Hi! I have a game with a hero and enemies. The enemies are prefabs that, when hit by a bullet, drop boxes that I have do touch on to apply some heal to the hero's life.
The logic problem is that when I have some boxes on the scene, I touch one of them the heal value should be 5, but what happens is that for some reason this runs for the number of boxes I have on the scene. For example: the scene has 4 boxes, and when I touch one of them the value applied is 20, or 4 * 5.
It is finding all objects with the tag "pack" when I touch one of them... but why?
What could be wrong?
Here is my code:
using UnityEngine;
using System.Collections;
public class Package : MonoBehaviour {
public GraphicalInterface gui;
public Camera cam;
void Start () {
cam = GameObject.Find("Camera").camera;
gui = cam.GetComponent<GraphicalInterface>();
}
void Update () {
foreach(Touch touch in Input.touches) {
if(touch.phase == TouchPhase.Began) {
Ray ray = cam.ScreenPointToRay(touch.position);
RaycastHit hit;
if(Physics.Raycast(ray, out hit) && hit.collider.gameObject.tag == "pack" && !gui.isGameOver) {
gui.ApplyHeal(5);
Destroy(hit.collider.gameObject);
}
}
}
}
}
I'd recommend adding some log messages to see what's going on. Print the positions of the colliders and boxes when you hit them. See how many touches are being processed.
Your answer
Follow this Question
Related Questions
Activating a single Prefab with the same tag using Raycast. 0 Answers
Script is reading from prefab instead of instance 1 Answer
Prefab mode doesn't show prefab, still shows old scene. 7 Answers
Trying to play other objects' sound and animations from Raycast hit 1 Answer
Difference between hit.collider.gameObject vs hit.transform.gameObject 2 Answers