Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

InvokeRepeating in OnMouseDrag

Discussion in 'Scripting' started by ctsteve123, Jul 31, 2008.

  1. ctsteve123

    ctsteve123

    Joined:
    Sep 13, 2007
    Posts:
    51
    Code (csharp):
    1.  
    2. var ball : Transform;
    3.  
    4. function OnMouseDrag(){
    5.    InvokeRepeating( "CreateBall" , 3 , 3 );
    6.  
    7. }
    8.  
    9. function CreateBall(){
    10.      
    11.     Instantiate( ball, transform.position , Quaternion.identity );     
    12.          
    13.          
    14. }
    I was hoping to create a ball every 3 seconds when the mouse button is kept pressed down. What is happening with the above code is that after 3 seconds a continuous creation of balls are created
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    OnMouseDrag is called every frame the mouse is dragging, so a new CreateBall() is being started once every frame. You'd want to use OnMouseDown instead, which is only called once. And then do CancelInvoke in OnMouseUp.

    --Eric
     
  3. ctsteve123

    ctsteve123

    Joined:
    Sep 13, 2007
    Posts:
    51
    Worked perfectly. Thanks for the quick response.