- Home /
Question by
ddd4175 · Jul 24, 2015 at 03:31 PM ·
dragbuildingdroptower defense
How do I attach an object to my pointer when i click a gui button?
Hello! I'm fairly new to coding and I don't really know how to do this, I'm trying to create a tower defense game an i'm in the process of making a build functionality in it but this is my first encounter to using GUI buttons, this is what I got so far
public List<GameObject> Build;
void OnGUI()
{
if (GUI.Button(new Rect(15, 15, 100, 50), "Red"))
{
Debug.Log("clicked");
GameObject g = (GameObject)Instantiate(Build[i]);
}
}
.....................
Here's is my code for the object
using UnityEngine;
using System.Collections;
public class dragobject : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
Cursor.visible = false;
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
void OnMouseUp()
{
Cursor.visible = true;
}
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220611232844im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D drag and drop a texture 0 Answers
Help starting a card app 0 Answers
Duplicate Object, by dragging? (SporeCreatureCreator Like) 0 Answers
Drag and drop files from the assets folder to another folder not working 0 Answers
how to active a button after drag? 2 Answers