Search Unity

After Coroutine the position is restarted

Discussion in 'Scripting' started by adri1992, Apr 7, 2016.

  1. adri1992

    adri1992

    Joined:
    Dec 14, 2015
    Posts:
    34
    Hi everyone!

    I've a problem and I haven't found any solution.

    I've this coroutine:

    Code (CSharp):
    1. public IEnumerator moveObjectBySquat()
    2.     {
    3.         Vector3 source = transform.position;
    4.         Vector3 target = new Vector3 (source.x, source.y - 0.5f, 0f);
    5.  
    6.         float startTime = Time.time;
    7.         while(Time.time < startTime + OVER_TIME)
    8.         {
    9.             transform.position = Vector3.Lerp(source, target, (Time.time - startTime)/OVER_TIME);
    10.             yield return null;
    11.         }
    12.   transform.position=target;
    13. }
    And I call the coroutine from the Update method:

    Code (CSharp):
    1. void Update(){
    2. if(booleanVar){
    3.          StartCoroutine(moveObjectToSourcePosition ());
    4.   }
    5.     }
    It works correctly, but when coroutine is finished the gameObject restarts to their original position automatically...

    Any idea?
     
    Last edited: Apr 7, 2016
  2. Hyblademin

    Hyblademin

    Joined:
    Oct 14, 2013
    Posts:
    725
    I don't really see any problems with this. Is the object's position ever set by anything else? Is the object physically dynamic?
     
  3. CrymX

    CrymX

    Joined:
    Feb 16, 2015
    Posts:
    179
    Are you sure your coroutine is lunched only one time ? Beacause in your coroutine i don't see booleanVar = false; You should name your properties too :)
     
  4. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,089
    @CrymX that's what I thought too - looks like it's launching hundreds of coroutines
     
  5. CrymX

    CrymX

    Joined:
    Feb 16, 2015
    Posts:
    179
    Before lunching the coroutine (to be sure) you cant stop it with StopCoroutine
     
  6. ericbegue

    ericbegue

    Joined:
    May 31, 2013
    Posts:
    1,353
    I'd suggest DOTween to move your game object over time. It's simple as:
    Code (CSharp):
    1. transform.DOMove(new Vector3(2,3,4),  1.0);