# Nested transform.position in Unity

The following code works so good , but it is so long.

How can I use a for loop to write a short script for any number of prefabs?

public GameObject prefab1;
public GameObject prefab2;
public GameObject prefab3;
float timCounter = 0f;

void FixedUpdate()
{
timCounter += Time.deltaTime;

float[]  r = {3,2,1};
float[]  f = {3,2,1};

//motion on a circle

float x = r[0] * Mathf.Cos(f[0] * timCounter);
float y = r[0] * Mathf.Sin(f[0] * timCounter);

float x1 = r[1] * Mathf.Cos(f[1] * timCounter);
float y1 = r[1] * Mathf.Sin(f[1] * timCounter);

float x2 = r[2] * Mathf.Cos(f[2] * timCounter);
float y2 = r[2] * Mathf.Sin(f[2] * timCounter);

float z = 0;

//position of a any prefab_n = position of prefab_(n-1) + Vector3(x,y,z)

prefab1.transform.position = new Vector3(x,y,z);

prefab2.transform.position = prefab1.transform.position + new
Vector3(x1,y1,z);

prefab3.transform.position = prefab2.transform.position + new
Vector3(x2,y2,z);
}

• When you say "nested," are you using parenting at all here? ie. is prefab3 a child of prefab2 which in turn is a child of prefab1? Also, are these really "prefabs" (archetypal assets in your project folder), or "instances" (objects you've actually spawned into your scene)? – DMGregory Nov 28 '19 at 1:38

Try something like this:

public GameObject[] prefabs;
public float[] r;
public float[] f;
float timeCounter = 0f;

void FixedUpdate()
{
timeCounter += Time.deltaTime;

var z = 0;
var numPrefabs = prefabs.Length;
var prevPosition = new Vector3(0, 0, 0);

for (var i = 0; i < numPrefabs; ++i)
{
var x = r[i] * Mathf.Cos(f[i] * timeCounter);
var y = r[i] * Mathf.Sin(f[i] * timeCounter);
var pos = new Vector3(x, y, z);

prefabs[i].transform.position = prevPosition + pos;

prevPosition = pos;
}
}


Here we have an array of game objects to proceed. You should link them to your game objects in Unity Inspector as well as setup r array and f array. Then this script will iterate over all game objects and set a position like in your script.