Touch Began Keeps Executing Multiple Times

When ever I try to use touch phases the code always happens multiple times. I would like to call a function on touch phase began only once. Instead it calls it 16 times! Any idea why? Thanks in advance :slight_smile:

    void Update () {
        if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
        {
            Debug.Log("sad");
        }
    }

Is this script only attached to a single GameObject? For kicks, try doing this instead, as Iā€™m not familiar with the GetTouch function:

void Update()
{
    if(Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
    {
        Debug.Log("sad");
    }
}

Just tried it out but I get the same problem. The debug log prints it out 16 times.

Oh wow I donā€™t know how, but the script did get attached to multiple objects.:face_with_spiral_eyes: Thank you for your help you rock!:slight_smile:

One quickie way to test for this problem in the future is to change your Debug to this:

Debug.Log(gameObject.GetInstanceID().toString + ā€œ: Your normal messageā€);

This will print out:
135829: Your Normal Message
and if you see this
124580: Your Normal Message

Then you know 2 different Game Objects called that function. Iā€™ve gotten into the habit of adding that to every Lineā€¦ Iā€™m constantly getting ā€œbugsā€ from multiple copies of a script running I never realized. You can Create a utility function in a C# script like this:

using UnityEngine;
using System.Collections;

public static class Utility
{
    public static void  MyDebug(GameObject obj, string txt)
    {
        Debug.Log(obj.GetInstanceID().ToString() + ": " + txt);
    }
}

// Call it like this
Utility.MyDebug(gameObject,"Message");