- Home /
Generate new blocks to land on
Dear unity Community,
I am trying to make a sort of endless runner, and I am trying to generate the next block when you touch the current block. So it will be endless. The distance has to be random but has to have a max so it is possible to make it and not to far away.
It is in 2D.
I wrote the following script, but with this the block only comes up on 1 place. The block taken is random but now I need the distance to be correct..
using UnityEngine;
using System.Collections;
public class createNewBlocks : MonoBehaviour {
public Transform[] teleport;
public GameObject[] prefeb;
public float XPosition = 0.0f;
public float YPosition = -2.6f;
void OnCollisionEnter2D(Collision2D coll) {
int tele_num = Random.Range(0,8);
int prefeb_num = Random.Range(0,2);
XPosition = XPosition += Random.Range (1, 20);
Debug.Log ("Xposition =" + XPosition);
Instantiate(prefeb[prefeb_num], teleport[tele_num].position = new Vector2(XPosition,YPosition), teleport[tele_num].rotation );
}
}
It would be great if someone could help me, thanks in advance!
Kind Regards,
Marijn
Answer by cdrandin · Jan 22, 2015 at 10:09 AM
XPosition = XPosition += Random.Range (1, 20);
is double assignment, wasteful. Should be...
XPosition += Random.Range (1, 20); // is also XPosition = XPosition + Random.Range (1, 20);
Are you sure teleport[] list have different transform values? Print them out. Maybe all of the position are just at one point and you are always going to place the blocks in the same spot because they are all the same values.
Oh thanks, you're right! But I am sure I have given the teleport[] diffrent transform values, they all have a unique position.
I am also getting the error "IndexOutOfRangeException", but not always. Sometimes it creates a new empty block clone, and sometimes it gives me the error above. it looks like it doesn't do anything with the prefab when it does create one?
It wouldn't hurt to valid your transforms. I don't know what exactly you are doing to populate your list so I can't know for certain why you are getting the exception from time to time. One idea could be you are removing from the list while iterating over it, thus co$$anonymous$$g off one short if you are removing and traversing at the same time.
cdrandin, I am so sorry. You were right all along, I was to sure of myself that I didn't made any mistakes but I switched the teleport and prefab section in the editor.. So the teleport was imported to the prefab haha? Seems legit that it didn't work. Anyway thanks for the effort! Really helped me out.
Your answer
Follow this Question
Related Questions
Generating a word out of an array, each has its own rarity. 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to instantiate prefabs at random postions in 2d 1 Answer
How do you make a spawner block? 1 Answer