Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

time between move decreases whit unity WaitForSeconds

I am trying to move a block -1 on the x axis and have delay in between moves

public class setmove : MonoBehaviour
{
 Transform trans
 private void Start()
{
 trans = GetComponet<Transform>();
}
private void Update()
{
 if(trans.position.x != -15 { StartCoroutine(wait(20)); }
//this is here to make new block and destroy old one
 if(trans.position.x <= -15 { GameObject .find("controller").GetComponet<set_make>().Start(); Destroy(this); }
private IEnumerator wait(int delay)
{
 yield return new WaitForSecondsRealTime(delay);
 trans.position = new vector3(trans.position.x-1, trans.position.y);
}
}

but there is no delay

i want it to wait but time in between decreases

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. A float will almost never be exactly == a value (floating point inaccuracies)
  2. Update runs once every frame => you are starting hundreds of concurrent coroutines every frame as long as the condition is met.

You probably should have only one single routine and e.g. do

// yes, start can be a Coroutine itself
// Unity will automatically run it as Coroutine if it returns IEnumerator
private IEnumerator Start() 
{
    while(transform.position.x > 15) 
    {
        yield return new WaitForSecondsRealtime(20);

        transform.position += Vector3.left;
    }

    // "Find" is capital "F"! C# is case sensitive
    // could probably also use `FindObjectOfType<set_make>
    // you should avoid calling `Start` from the outside
    // It is a " magic" message and will anyway be called by the engine automatically
    // so it is at best confusing to call it from anyway else again
    GameObject .Find("controller").GetComponet<set_make>().Start();
    // note that if using "this" You only destroy the component, not the obbect
    Destroy (this.gameObject) ;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading