0
\$\begingroup\$

So I have this script - Which should spawn diamonds

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawn : MonoBehaviour
{
    public GameObject Diamond;
    public int DiamondCount;
    public int Xpos;
    public int Zpos;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(Spawning());
    }
    IEnumerator Spawning()
    {
        while (DiamondCount < 5)
        {
            Xpos = Random.Range(24, -17);
            Zpos = Random.Range(-17, 24);
            Instantiate(Diamond, new Vector3(Xpos, 0.94f, Zpos), Quaternion.identity); 
            yield return new WaitForSeconds(0.1f);
            DiamondCount +=1;
        }
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}

This script is attached to a game manager object And when I run my game the diamonds do not spawn Why is this and how do I fix it

Inspector

I

\$\endgroup\$
0
0
\$\begingroup\$

Issue fixed I changed the while loop to a for loop and it works now

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Your while condition was DiamondCount < 5 - but your DiamondCount was initialized to 5. 5 is not less than 5, so the while condition instantly failed. \$\endgroup\$
    – DMGregory
    Mar 10 at 17:02
  • \$\begingroup\$ ah just seen that such a basic error but the for loop works now \$\endgroup\$
    – elliot727
    Mar 10 at 17:04
  • 1
    \$\begingroup\$ Because your for loop has a local variable that you probably set to 0 or 1. You should have a second variable in your scene in either case that keeps track of how many diamonds are spawned and the other one how many are allowed at the same time. \$\endgroup\$
    – Zibelas
    Mar 10 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.