Search code examples
unity-game-engineunity3d-2dtoolsunity-ui

How to make Unity UI object draggable when the objects are instantiating at runtime?


I am working on a management game where every user has some specific characters in save files. I am instantiating these characters inside a panel, I want the user to choose one of the cards and drag it to some specific point. I am able to make a drag script for the object that is already in a scene. But how to achieve the same thing if objects are generating at runtime? I just need some idea how to do it. here's my current code to drag UI object.

    public void OnDrag(){
    btn.transform.position = Input.mousePosition;
}
public void EndDrag(){
    if (btn.transform.position.x -500 <50 || btn.transform.position.x -500 > -50) {
        //btn.transform.position = new Vector3 (-10, 10);
        rt.anchoredPosition = new Vector3 (500, 100, 0);
    }
    else{
        rt.anchoredPosition = new Vector3 (-10, -10, 0);
    }
}

Solution

  • At the time you Instantiate your GameObject obj, do:

    obj.addComponent("YourScript");
    

    where YourScript is your script, which you have written, that attached to a GameObjects makes it draggable..

    Alternatively, you instantiate a prefab, attach the script to the prefab through the editor.

    This is preferrable because addComponent() will get deprecated in the next versions.

    I also recommend to keep a List<YourInstantiatedObjectType> in the parent.