Change speed of spawned objects in another script in c#


In my game, multiple game objects are spawned in an increasing interval, and moving from left to right. I’m trying to change the speed of these spawned clones over time.

My TouchableObject (spawned objects) script (a part of it):

public float carSpeed = 1.1f;

void Start() {
rb = GetComponent ();
rb.velocity = new Vector2 (carSpeed, rb.velocity.y);
Debug.Log (carSpeed);

I want to increase the speed of these spawned objects every 30 seconds. But when I do that in this script, it isn’t working, because new objects are spawned, with the startspeed of 1.1f. When I removed the startspeed, the objects aren’t moving, so that wasn’t working too.

So I tried to change the carSpeed in my Timer script:

public class Timer : MonoBehaviour {

private float timer;
private Spawner spawner;
private Spawner1 spawner1;
private Spawner2 spawner2;
private Spawner3 spawner3;
private Spawner4 spawner4;
private Spawner5 spawner5;

public TouchableObject touchableObject;

// Use this for initialization
void Start () {
	spawner = GameObject.FindObjectOfType<Spawner>();
	spawner1 = GameObject.FindObjectOfType<Spawner1>();
	spawner2 = GameObject.FindObjectOfType<Spawner2>();
	spawner3 = GameObject.FindObjectOfType<Spawner3>();
	spawner4 = GameObject.FindObjectOfType<Spawner4>();
	spawner5 = GameObject.FindObjectOfType<Spawner5>();
	touchableObject = GameObject.FindObjectOfType<TouchableObject>();

// Update is called once per frame
void Update () {
timer += Time.deltaTime;
if (timer >= 30) {
timer = 0;


But that isn’t working. I get the message ‘NullReferenceException: Object reference not set to an instance of an object’.

Can anyone please help me? I don’t know what I’m doing wrong.

Thank you very much!


You seem to be doing it in an advanced way, why not, on the same script thats already attached to your clones, add this part to it. Simply after it spawns (so in its Start), every 30 seconds, run a function on the script, that will change its speed manually.

Or, if you really wanna do it from another script, then just either have each clone watch a global script’s speed, and every 30 seconds, change the global speed of that script, and automatically, all clones will comply. Or as each clone is spawned, put them as a child to a parent object, like a blank game object that sits off screen in the world, then, every 30 seconds in your master script, access that parent, and run a for loop through each element in that game object, since you know its only your clones in there, access their scripts and change the speed manually.

I would say the best way would probably be the first way with just updating the speed within the same script.