Question by
houtarou_oreki · Nov 16, 2021 at 12:55 PM ·
unity 2dfor-loop
loop and instantiate
hello guys, I'm new at using unity and a newbie programmer. I was wondering if you can help me out. I'm currently making a counting game for my nephew. so here it goes, the game will generate how many objects will be generated randomly (example 13 apples). what I wanted is after looping at 10 it will break and continue again from a new line. the output of my code generates 13 by column each row.
Comment
Best Answer
Answer by Hellium · Nov 16, 2021 at 01:02 PM
float initialXPosition = 0;
float x = initialXPosition ;
float y = 0;
int maxApplesPerRow = 10; // Value **must** be greater than 0
int appleCount = 13;
Transform parent = GameObject.FindGameObjectWithTag("respawn").transform;
for(int apple = 1 ; apple <= appleCount ; ++apple)
{
Vector3 spawnPos = transform.position + new Vector3(x, y, 0);
GameObject gobject = Instantiate(objectPrefab, spawnPos, Quaternion.identity);
gobject.transform.SetParent(parent , false);
objects.Add(gobject);
x += objectPrefab.transform.localScale.x + spacing;
if(apple % maxApplesPerRow == 0)
{
y -= objectPrefab.transform.localScale.y + spacing;
x = initialXPosition;
}
}
Your answer

Follow this Question
Related Questions
My unity STOPS RESPONDING when this function is activated 0 Answers
Multiplying the same enemy 0 Answers
For Loop: Different count of objects are added to lists 0 Answers
If statement in for loop not working after fail 0 Answers
How to create a spinwheel with pre-determined results after spin. 1 Answer