How can I spawn and drag from a button click?

I’m trying to make a button to spawn robots where you hold down on the button, instantiate, and be able to drag from there to where you want it. The problem is in this script it only instantiates and drops the robots directly below it.

	if (GUI.Button (setPositionAndSize(sbposx, sbposy, sbbuttonw, sbbuttonh), SwatbotTexture, ""))
	{
		print(Input.mousePosition);
		Vector2 p = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y));
		print(p);
		print(p.x);
		print(p.y);
		
		Instantiate(playerBots[0],new Vector2(p.x,p.y),Quaternion.identity);
	}
  1. Capture the position of the mouse after the mouse is up.

  2. Spawn the robot to the location.

    if(GUI.Button(setPositionAndSize(sbposx,
    sbposy,
    sbbuttonw,
    sbbuttonh),
    SwatbotTexture,
    “”)
    {
    if(Input.GetMouseButtonUp(1))
    {
    Vector2 spawnPoint = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x,
    Input.mousePosition.y));
    Instantiate(playerBots[0],
    spawnPoint,
    Quaternion.identity);
    }
    }

GUI.Button() execute on the mouse up, so your current code is creating the object as the button is released. You need it to capture the mouse down. A way to do that is to use the current GUI event and check for the MouseDown event. It is kinda ugly to put the dragging code inside of OnGUI()…partly since the function gets called multiple times per frame. So here is some example code. I recommend you test it first on an new scene then take the logic and integrate it back into your code. To use:

  • Start a new scene
  • Create an empty game object
  • Drag and drop a prefab on the ‘prefab’ variable
  • Hit run

#pragma strict

public var prefab : Transform;

private var spawn : Transform;
private var rect = Rect(0,0,100,50);

function Update() {


	if (Input.GetMouseButton(0) && spawn != null) {
		var pos = Input.mousePosition;
		pos.z = -Camera.main.transform.position.z;
		spawn.transform.position = Camera.main.ScreenToWorldPoint(pos);
	}
	
	if (Input.GetMouseButtonUp(0)) {
		spawn = null;
	}

}
function OnGUI() {
	var e = Event.current;
	
	if (e.type == EventType.MouseDown && rect.Contains(e.mousePosition)) {
		var pos = Input.mousePosition;
		pos.z = -Camera.main.transform.position.z;
		pos = Camera.main.ScreenToWorldPoint(pos);
		spawn = Instantiate(prefab, pos, Quaternion.identity);
	}
	
	GUI.Button (rect, "Button");
}

Note that we are not using the button as a button here…the call just displays the button. If you like, you can replace it with a GUI.DrawTexture to draw the texture of your choice. Your code creates the object with the ‘z’ position at 0.0, but does it as a side-effect. Your world position code would also require an Orthographic camera. I changed the position code so that it will work for both an Orthographic and Perspective camera.

@gimoj how can i do this with with canvas button?