- Home /
Unable to spawn and drag via button click
I want to make a system where on the button click i am able to spawn the prefab and drag it to the place i want without taking my finger off the screen. For that i have made a drag script which is attached to my prefab :-
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Script_PC_drag : MonoBehaviour {
     Vector3 dist;
     float posX;
     float posY;
 
     void OnMouseDown()
     {
         dist = Camera.main.WorldToScreenPoint (transform.position);
         posX = Input.mousePosition.x - dist.x;
         posY = Input.mousePosition.y - dist.y;
     }
 
     void OnMouseDrag()
     {
         Vector3 curPos = new Vector3 (Input.mousePosition.x - posX, Input.mousePosition.y - posY, dist.z);
         Vector3 worldPos = Camera.main.ScreenToWorldPoint (curPos);
         transform.position = worldPos;
     }
 }
Right now i have a button and upon clicking the button, i am able to instantiate a prefab at a location and then drag it from there. Can anyone please direct me as to how to make the system??
Answer by Hynoer · Nov 06, 2017 at 02:49 PM
Hey,
I strongly recommend to use the dedicated event offer by Unity PointerEventData .
It's simpler and very quick to use, you can find some example on the web.
here mine :
 public class PanelMouse : MonoBehaviour, IPointerClickHandler{
 
     public GameObject toSpawn;
 
     public void OnPointerClick(PointerEventData eventData)
     {
 
         GameObject spawned = Instantiate (toSpawn);
         spawned.transform.position = Camera.main.ScreenToWorldPoint(eventData.position) + new Vector3(0,0,10);
         Destroy (spawned,3f);
     }
 }
this script has to be used on the button or the collider of the gameobject??
Your answer
 
 
             Follow this Question
Related Questions
Drag and Drop w/ Snapping 0 Answers
Drag and Drop on RTS camera 1 Answer
Drag Item Scaling on Phone 0 Answers
Drag item on screen once spawned. 0 Answers
How to move UI image between panels 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                