- Home /
Move an object to mousePosition
I created a cube on a plane. The cube's position is (2, 3, 0.5). Now I added a script to the cube to move the cube to any position when I click on the screen.
 var clicked : int = 0;
 
 function OnGUI() {
     var e : Event = Event.current;
     if(e.button == 0 && e.isMouse){
         //Debug.Log("Left Click");
         this.clicked = 1;        
     }
 }
 
 function Update () {
     if (this.clicked == 1)
     {
         print(transform.position);
         transform.position = Vector3(Input.mousePosition.x, Input.mousePosition.y, 0.5);
         this.clicked = 0;
     }
 }
But the result confused me. Even when I click 5mm left to the cube I get these new coordinates: (2.5, 3, 0.5) BUT also (211, 257, 0.5)
Why is my mouseclick executed two times? And why is the second position so far away?
Answer by Graham-Dunnett · Jul 01, 2013 at 01:02 PM
OnGUI() can be called multiple times per frame - once for each event. Check to see what the event is. 
Answer by Tipo · Jul 01, 2013 at 01:09 PM
Thanks for help. I changed it now a bit but the result is the same. function Update () {
     if (Input.GetMouseButtonDown(0))
     {
         //print(transform.position);
         transform.position = Vector3(Input.mousePosition.x,Input.mousePosition.y,0);
         //this.clicked = 0;
     }
 }
The new coordinates are also far far away and the event is also fired twice. I attached the script only to my cube and nothing else. So it can't be that it is instantiated more then once.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                