- Home /
Create a button to instantiate and drag GameObject
Hello
This is the first time using Unity Answers, I search this specific question but didn't find any thread. The closer I got was this but I want to use the new UI system.
I want to create an UI button that on MouseDown instantiates a prefab and let me drag that prefab. I managed to instantiate the prefb with no problems, but when I click the button I have to click a second time to drag the prefab. On the UI button I have an event trigger with on PointDown that runs the Instantiate function from this script.
public GameObject prefabToInstantiate;
public void Instantiate(){
Vector3 mousePos = Input.mousePosition;
mousePos.z = 10;
Vector3 objPos = Camera.main.ScreenToWorldPoint(mousePos);
print ("Mouse is down");
if (GameObject.FindWithTag("GameLogic").GetComponent<gamePhasesScript>().IsPlayerPhase){
GameObject prefabToInstantiateClone = (GameObject) Instantiate(prefabToInstantiate,objPos,Quaternion.identity);
}
}
I have the drag script attached to the prefab.
Answer by AlwaysSunny · Apr 26, 2015 at 07:24 PM
"I have the drag script attached to the prefab."
That's not the best place for it. Code responsible for dragging objects and interacting with the 3D world in similar ways should be part of some consolidated input manager or player controller.
Don't use Finds to find your references unless you have no choice. Looks like your "GameLogic" object might make a good singleton. Then you can reference the instance of it from any script easily.
In any case, the code responsible for dragging should have an "activeObject" variable which is a reference to the object you are currently dragging. Your button can instantiate the object, then tell the singleton input manager that it's the active dragged object.