Search Unity

Touch event on prefab component

Discussion in '2D' started by tle94, Aug 18, 2017.

  1. tle94

    tle94

    Joined:
    Dec 8, 2015
    Posts:
    13
    Hello everyone,

    I have wrote a small 2D game with UI components.

    I have a Canvas with 3 child components as bellow image:

    upload_2017-8-18_11-57-58.png

    And I also have some prefabs number_x with same properties like bellow:
    upload_2017-8-18_12-0-46.png upload_2017-8-18_12-1-18.png

    I added an C# script (ButtonEventController) into prefab "number_1" as above image (only for number_1) with Update() function like bellow:

    void Update () {
    // Handle native touch events
    foreach (Touch touch in Input.touches) {
    HandleTouch(touch.fingerId, Camera.main.ScreenToWorldPoint(touch.position), touch.phase);
    }

    // Simulate touch events from mouse events
    if (Input.touchCount == 0) {
    //if (Input.GetMouseButtonDown(0) ) {
    HandleTouch(10, Camera.main.ScreenToWorldPoint(Input.mousePosition), TouchPhase.Began);
    //}
    //if (Input.GetMouseButton(0) ) {
    HandleTouch(10, Camera.main.ScreenToWorldPoint(Input.mousePosition), TouchPhase.Moved);
    //}
    if (Input.GetMouseButtonUp(0) ) {
    HandleTouch(10, Camera.main.ScreenToWorldPoint(Input.mousePosition), TouchPhase.Ended);
    }
    }
    }

    private void HandleTouch(int touchFingerId, Vector3 touchPosition, TouchPhase touchPhase) {
    switch (touchPhase) {
    case TouchPhase.Began:
    // TODO
    break;
    case TouchPhase.Moved:
    // TODO
    break;
    case TouchPhase.Ended:
    tickTransform = Instantiate (tickPrefab) as Transform;
    tickTransform.position = new Vector3 (transform.position.x, transform.position.y, transform.position.z);
    tickTransform.SetParent (gameObject.transform);

    break;
    }
    }

    When my project runs, click on Btn_submit button, I will Instantiate prefabs number_1,2,3..5 and set their parent is Canvas. This is OK. But my problem is I can't handle touch (or mouse click) event on these prefabs. If I click wherever on Canvas, number_2, number_3,number_4 or number_5, the HandleTouch function always be triggered. I just want this event only be triggered if I click on number_1.

    I think this is because the prefabs "number_x" are child components in Canvas. Am I right? And how I can handle Touch or mouse click events on these child prefabs components inside a Canvas ? Please advise.

    Thank you so much.
     

    Attached Files:

  2. tle94

    tle94

    Joined:
    Dec 8, 2015
    Posts:
    13
    I have resolved this problem. I need to attach collider to each prefab. Then use OnMouseDown to detect touch on that particular prefab.