0

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);
    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
  • So, what classes or objects have you written in your project? Character ? CharacterCard ? Can one character have more than one Character Card or is it 1:1 ? Are the cards contained where? – Attersson May 12 '18 at 17:50
  • Cards are instantiating as images. I can already Instantiate cards and put them in a panel. Everything is working fine, Only thing i need to know is that how can i write a draggable script for an object that instantiate at runtime. – ghayoornaqvi May 12 '18 at 17:53
  • @ghayoor you can create a prefab of your object and attach dragging-script to this prefab. And when you'll instantiate your object, it will already has your script – ThePyzhov May 12 '18 at 18:02

1 Answers1

-1

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.

Attersson
  • 4,755
  • 1
  • 15
  • 29