- Home /
How do I move a clicked and selected object to a clicked position
I am trying to move objects to different positions. I have 3 objects. What I want is the player clicks and selects 1 object and then clicks again to move the selected object to the clicked position. I am using raycast to do this, but not working. Kindly help.
Code:
void Update () { GameObject tempObject = null; if (Input.GetMouseButtonDown(0)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { //Debug.Log(hit.collider.gameObject.name);
if (hit.collider.gameObject.name == "BigDisc-2")
{
Debug.Log("BigDisc2 selected");
tempObject = hit.collider.gameObject;
Debug.Log(tempObject);
}
if (hit.collider.gameObject.name == "Peg2" && tempObject != null)
{
Debug.Log("Peg2 selected");
Debug.Log("Move Disc");
}
}
}
}
Answer by CoryButler · Apr 07, 2017 at 12:42 PM
First, you need to define tempObject outside of the Update function, not within it. Something like this:
public class MoveToClicked : MonoBehaviour {
GameObject tempObject = null;
// Update is called once per frame
void Update ()
Then, add the following code after Debug.Log("Move Disc").
tempObject.transform.position = hit.collider.transform.position;
BigDisc-2 will jump to Peg2's position.
Thanks for your help. It was initializing every time when it was calling Update. I just missed that.
Thanks a lot, that was really helpful. I was really trying to find how we first select then move.