- Home /
Problems editing a level from script
Hello, I'm trying to create levels dynamically. To do so, I have created a scene and I edit the ammount of components I have in the scene using a script. Here's the code I'm using:
public class BuildScene : MonoBehaviour
{
public Transform square;
void Start()
{
int numFilas = ApplicationModel.numberRows;
int numObj = 3;
float posY = 2.5f;
for (int i = 0; i < numFilas; i++)
{
for (float j = 0; j < numObj; j++)
{
float posX = -0.9f;
Instantiate(square);
square.transform.localScale = new Vector3(0.6f, 0.6f, 0.1f);
square.transform.position = new Vector3(posX+j, posY-i, 0);
}
}
}
Public Transform square is a prefab of a 3dcube with a material.
numberRows changes deppending on the button you press (level 1 = 1 row, level 2 = 2 rows, etc.).
The problem is that the first time you enter a level the last cube of the last row doesn't appear, or is in a wrong position, but the second time you enter into that level it works perfectly. Any ideas?
If you want I pass you the project (is really small right now) so you can execute it.
Answer by Landern · Nov 18, 2016 at 02:28 PM
You need to use the instantiated square's new reference instead of the one you're basically copying from the inspector.
Change your Start method to use a local variable that is a reference to the new game object. This will also lessen the complexity of the code a bit since you're already dealing with a transform which you where before... anywho
void Start()
{
int numFilas = ApplicationModel.numberRows;
int numObj = 3;
float posY = 2.5f;
for (int i = 0; i < numFilas; i++)
{
for (float j = 0; j < numObj; j++)
{
float posX = -0.9f;
Transform newSquare = Instantiate(square);
newSquare.localScale = new Vector3(0.6f, 0.6f, 0.1f);
newSquare.position = new Vector3(posX+j, posY-i, 0);
}
}
}
Now stuff looks like (1 row):
And now 6 rows: