Search Unity

Changing Update C#

Discussion in 'Scripting' started by tutukas33, Dec 27, 2016.

  1. tutukas33

    tutukas33

    Joined:
    Apr 7, 2013
    Posts:
    28
    Does any one know how to change Update to something else for example:
    I have this code which lets my object move.... and i would like to change that code from (to make it stop)
    THIS
    transform.position += Vector3.up * Time.deltaTime*speed;
    TO THIS
    transform.position -= Vector3.up * Time.deltaTime*speed;
    On Collision. This is my code:
    Code (csharp):
    1.  
    2.  
    3.     float speed = 5.0f;
    4.    
    5.  
    6.     void Update() {
    7.        
    8.         transform.position += Vector3.up * Time.deltaTime*speed;
    9.     }
    10.     void OnCollisionEnter2D(Collision2D collision) {
    11.         DestroyObject(collision.gameObject);
    12.         transform.position -= Vector3.up * Time.deltaTime*speed;
    13.  
    14.  
    15.     }
    16.  
    17.     public void SetSpeed(float modifier)
    18.     {
    19.         speed = 5.0f + modifier;
    20.     }
    21.  
    22. }
    23.  
    24.  
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,175
    I would create a variable, like direction, which is either 1 or -1, in CollisionEnter2D I would set it to -1, then I'd multiply the whole Vector3.up * Time.deltaTime * speed thing with it
     
  3. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,091
    not sure if this is what you're after. but it might get you on the right path

    Code (CSharp):
    1. float speed = 5.0f;
    2. bool isFwd = true;
    3.  
    4.     void Update() {
    5.        if(isFwd)
    6.        {
    7.         transform.position += Vector3.up * Time.deltaTime*speed;
    8.         }else
    9.         {
    10.         transform.position -= Vector3.up * Time.deltaTime*speed;
    11.         }
    12.     }
    13.    
    14.     void OnCollisionEnter2D(Collision2D collision) {
    15.         DestroyObject(collision.gameObject);
    16.         isFwd = false;
    17.     }
    18.     public void SetSpeed(float modifier)
    19.     {
    20.         speed = 5.0f + modifier;
    21.     }
    22. }
     
unityunity