Search Unity

While loop not working?

Discussion in 'Getting Started' started by LifeInDevelopment, Sep 2, 2016.

  1. LifeInDevelopment

    LifeInDevelopment

    Joined:
    Jan 17, 2016
    Posts:
    2
    Hi, I havent been on unity for a long time and I've forgot quite alot. Whenever I try to run this it keeps giving me the error: 'Assets/Scripts/RoundScript.cs(8,14): error CS1624: The body of `RoundScript.Start()' cannot be an iterator block because `void' is not an iterator interface type'.

    Heres the c# script:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class RoundScript : MonoBehaviour {
    5.     public int score;
    6.     public GameObject enemy;
    7.  
    8.     void Start () {
    9.         score = 0;
    10.  
    11.         while (true) {
    12.             yield return new WaitForSeconds (5.0f);
    13.             Instantiate (enemy, new Vector3 (25, 0.5, Random.Range (-6, 6)));
    14.             score = score + 1;
    15.         }
    16.  
    17.     }
    18.  
    19. }
    20.  
     
  2. Iron-Warrior

    Iron-Warrior

    Joined:
    Nov 3, 2009
    Posts:
    838
    Hey Life, your while loop in itself is fine. The issue here is that you can't use yield commands from within a void method (void Start()). Instead, they can only be in methods with the return type IEnumerator. This is because Unity uses IEnumerator to drive their Coroutine system. If you modify the method to be IEnumerator Start, this will work. Note that normally to run a Coroutine method, you need to call StartCoroutine.
     
    LifeInDevelopment, Ryiah and Kiwasi like this.