Ask about touch event on image component in Canvas (2d)

Hello,

I have wrote a small 2d game that used Canvas.

I added 3 image components to Canvas (called UIContainer) as below image:

Then I added CSharp script (TouchDuckPlayAudio) to main_img to play an audio when touch event occurs. But when I touch anywhere on Scene, the audio also run. I expected this audio only run when I touch on main_img.

I googled and knew that should use Events System and Raycasters to detect and process touch event on child components in Canvas. But these references are not clear for me, there are some questions I hope you can help me:

  1. I should add scripts to Canvas (UIContainer) instead to main_img, right ?
  2. Could you give me small tutorial / example about touch event with Events System and Raycasters (someone shows touch event on Button in Canvas, but I think it is different with my case - I used image component) ?

Thank you very much,

  1. It depends on what script is about, If it deals with more than one objects under canvas, you should always add it to parent (Canvas). If it is object specific, for example if it only deals with other components of same object then you attach it to specific child object instead of parent.

In your case, you need to attach Touch Input Module to your event system to receive touch input on mobile devices (for older versions of Unity). And to interact with main_img, this object should have a button component on it.

Hope this helps.