0

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

1 Answers1

3
  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) ;
}
derHugo
  • 83,094
  • 9
  • 75
  • 115