2D Toolkit Forum

2D Toolkit => FAQs => Topic started by: 2djim on June 04, 2013, 11:37:06 pm

Title: building your own ui components in unity script
Post by: 2djim on June 04, 2013, 11:37:06 pm
Is building your own ui components in unity script possible ? the examples for listening to events appear to be in c.
If this is possible in unity script how would an example look.
thanks
Title: Re: building your own ui components in unity script
Post by: unikronsoftware on June 05, 2013, 10:09:48 am
Definitely possible.
Here's a port of the tk2dUIDragItem class to JS to get you started.

* Remember to run SetupForJS, otherwise the classes won't be accessible from JS.
* Also note - apart from the usual suspects, variable & function definition syntax, there isn't REALLY any difference there.

Code: [Select]
#pragma strict

class DragItem extends tk2dUIBaseItemControl {

private var offset : Vector3 = Vector3.zero; //offset on touch/click
private var isBtnActive : boolean = false; //if currently active

function OnEnable()
{
    if (uiItem != null)
    {
        uiItem.OnDown += ButtonDown;
        uiItem.OnRelease += ButtonRelease;
    }
}

    function OnDisable()
    {
        if (uiItem != null)
        {
            uiItem.OnDown -= ButtonDown;
            uiItem.OnRelease -= ButtonRelease;
        }

        if (isBtnActive)
        {
            if (tk2dUIManager.Instance != null)
            {
                tk2dUIManager.Instance.OnInputUpdate -= UpdateBtnPosition;
            }
            isBtnActive = false;
        }
    }



    private function UpdateBtnPosition()
    {
        transform.position = CalculateNewPos();
    }

    private function CalculateNewPos() : Vector3
    {
        var pos : Vector2 = uiItem.Touch.position;
        var worldPos : Vector3 = tk2dUIManager.Instance.UICamera.ScreenToWorldPoint(new Vector3(pos.x, pos.y, transform.position.z - tk2dUIManager.Instance.UICamera.transform.position.z));
        worldPos.z = transform.position.z;
        worldPos += offset;
        return worldPos;
    }

    /// <summary>
    /// Set button to be down (drag can begin)
    /// </summary>
    public function ButtonDown()
    {
        if (!isBtnActive)
        {
            tk2dUIManager.Instance.OnInputUpdate += UpdateBtnPosition;
        }
        isBtnActive = true;
        offset = Vector3.zero;
        var newWorldPos = CalculateNewPos();
        offset = transform.position - newWorldPos;
    }

    /// <summary>
    /// Set button release (so drag will stop)
    /// </summary>
    public function ButtonRelease()
    {
        if (isBtnActive)
        {
            tk2dUIManager.Instance.OnInputUpdate -= UpdateBtnPosition;
        }
        isBtnActive = false;
    }
}