x


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);
            }
        }
    }
}

}

more ▼

asked Mar 21 '11 at 11:33 PM

hgbimonti gravatar image

hgbimonti
1 1 1 1

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.

Mar 22 '11 at 06:24 PM flaviusxvii
(comments are locked)
10|3000 characters needed characters left

0 answers: sort oldest
Be the first one to answer this question
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1536
x1260
x228
x161
x17

asked: Mar 21 '11 at 11:33 PM

Seen: 698 times

Last Updated: Mar 21 '11 at 11:33 PM