0

I want to select sprites in unity mobile. So I think a way is add button component to sprite but when I do that, it does not work.

I did the same things for normal buttons adding script in on click function and button works. But can't do same thing in sprite.

Am i missing something?

If anyone knows another better way to select game objects in mobile please tell for example I want upgrade a game object by clicking on it.

like this

behzad
  • 801
  • 3
  • 15
  • 33

1 Answers1

1

I'm not sure if I totaly understand what is your goal, but if you just want to detect if user clicked game object on mobile you can use Input.touches

void Update()
{
    for (int i = 0; i < Input.touchCount; i++)
    {
        if (Input.GetTouch(i).phase == TouchPhase.Began)
        {
            Vector3 p = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);

            int layerMask = 1 << objectLayer;
            Ray ray = new Ray(p, Vector3.forward * distance);
            RaycastHit2D hit = Physics2D.GetRayIntersection(ray, distance, layerMask);

            if (hit.collider != null)
            {
                YourObject obj = hit.collider.GetComponent<YourObject>();
                if (obj != null)
                {
                    // player clicked on the object
                }
            }
        }
    }
}

I did not test that code but it should roughly work for 2D, objectLayer is the index of the layer of your object and distance is how far should the Raycast go.

I have never done somthing like this for 3D but I guess it would be simillar.

Szymig
  • 555
  • 5
  • 9
  • yeah , its good, but in which part code knows that touch overlap with gameobject? the game object is moving around – behzad Aug 26 '18 at 14:55
  • right, so I added the detection part for 2D, if your game is 3D then the Raycasting part might change a little – Szymig Aug 26 '18 at 15:39