Setting rigidbody.velocity of all child objects to "x".

I got a script where I spawn mountains for a background.
These mountains go to the left, and have a velocity of “x”.

I use a mountain spawner script. I instantiate the mountains, make them child of the spawner, and give them a certain velocity.
Sometimes I will disable (SetActive(false)) the spawner. At this moment everything is okay, however when I re-enable it, all mountains that were previously placed have now a velocity of 0.

Unless there is a way to bypass this behaviour above, I would like to know how I can set the velocity of all mountains previously spawned to “x”.

I tried using the following script:

    void OnEnable()
        Rigidbody2D m[] = GetComponentsInChildren<Rigidbody2D>();
        foreach (Rigidbody2D mnt in m)
            m.velocity = new Vector3(-1 * mountainSpeed, 0, 0);

As you may have guessed, it just doesn’t work at all. It gives me an error:

Error	CS0650	Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.	

I do not know how I should do this. When I instantiate the mountains, I do not keep track of them (at least I think not"), and just place them as a child of a spawner.

If you know the solution/answer, and it involves some “complex stuff”, I will be glad if you explain what you did, so I will not have to ask this again :smiley:

Thanks for the attention!!!

The error actually tells you what is wrong. To declare a managed array, the array rank specifier ‘’ precedes the variable’s identifier ‘m’ i.e. ‘Rigidbody2D m =’ and not ‘Rigidbody2D m =’.

Alternately, just use 'var m = '.

Rigidbody2D m = …
Should be

Rigidbody2D[] m = ...

And then your loop looks stange.

m.velocity = ...

Should be

mnt.velocity = ...

I would have the children handle their own velocity. That is each mountain can have a Mountain script attached and can refer to the speed setting in its parent.

// In the mountain script
Vector3 fixedVelocity =;
Rigidbody rigidbody = null;
void Awake() {
   fixedVelocity =  Spawner.fixedVelocity;
   rigidbody = gameObject.GetComponent<Rigidbody>();
void OnEnable() {
   rigidbody.velocity = fixedVelocity;

// In your spawner script
static Vector3 fixedVelocity;
const float mountainSpeed = 10f;

void Awake() {
   Spawner.fixedVelocity = Vector3.left * mountainSpeed;