Hello!
I have this (for me) weird problem in my code. What I’m trying to do is generate a level for my platformer game and I have 2 scripts to do that.
SegmentCreation.cs (from now on SGC) for creating a segment 31 blocks wide
and
LevelGeneration.cs (from now on LG) for checking where the player is and if another segment should be generated
The problem is that when LG calls SGC’s function CreateFloor() it instantiates a bunch of blocks all on the same location. I figured it’s because the width of the block isn’t calculated at that time or something like that, so I tried solving it by changing the script execution order, which didn’t help. The coroutine you see at the bottom did though.
Any ideas why that is or comments about the code in general will be appreciated.
Thanks!
public class SegmentCreation : MonoBehaviour {
public GameObject groundBlock;
double segmentSize;
Vector3 blockSize;
public int numBlocks = 31;
// Use this for initialization
void Start () {
blockSize = groundBlock.GetComponent<BoxCollider2D> ().size;
segmentSize = numBlocks * blockSize.y;
}
// Update is called once per frame
void Update () {
}
public void CreateFloor(){
//Middle
Instantiate (groundBlock, new Vector3(0, -3, 0), Quaternion.identity);
//Blocks left
for(int i = 1; i <= (numBlocks-1)/2; i++){
Instantiate (groundBlock, new Vector3(-3*i*blockSize.x, -3, 0), Quaternion.identity);
}
//Blocks right
for(int i = 1; i <= (numBlocks-1)/2; i++){
Instantiate (groundBlock, new Vector3(3*i*blockSize.x, -3, 0), Quaternion.identity);
}
}
}
Problem code
public class LevelGeneration : MonoBehaviour {
SegmentCreation Sgc;
// Use this for initialization
void Start () {
Sgc = Camera.main.GetComponent<SegmentCreation> ();
Sgc.CreateFloor ();
}
// Update is called once per frame
void Update () {
}
}
“Fixed code”
public class LevelGeneration : MonoBehaviour {
SegmentCreation Sgc;
// Use this for initialization
void Start () {
StartCoroutine ("Wait");
}
// Update is called once per frame
void Update () {
}
IEnumerator Wait(){
yield return new WaitForEndOfFrame();
Sgc = Camera.main.GetComponent<SegmentCreation> ();
Sgc.CreateFloor ();
}
}
Edit: Using Awake() instead of Start() in SGC also fixes the problem without a need for a coroutine in LG