Smartest way manipulate multiple gameobjects with a single variable?

Let me explain what I’m trying to do, there might be an alternative. I am attempting to write a 3D endless-runner game from scratch. I have multiple platform pieces moving front to back (on a Z-axis) to simulate movement, movement is scripted internally to each platform because that was much simpler code. (moving multiple random pieces from one script was a nightmare).

I want the game to gradually go faster and be able to change the game speed on the fly …so I want to base all the platform’s speeds on some kind of global variable “GroundSpeed”. The easy but super BAD solution was to put:

(pseudo code, not tested)

void Update {
     foreach (go in platforms) {
          go.GetComponent<platform>().speed = GroundSpeed;
     }
}

You never put GetComponent in Update, what is the alternative?

You could GetComponent once in Start() and save the result.

Are you referring to the Start() in the script for the platforms, or the script that holds the global variable?

In whichever script has the Update() method you posted. The saved result I described is to use in Update()

Flip this on its head. Instead of updating the platform speed every frame, have the platforms grab their speed from the manager. Use something like a singleton or static to allow global access.

3 Likes

To expand on that: you already have a property called “speed” in your platform class. Just put “static” in front of the declaration of that (e.g. “public static float speed”). This means that there is only one speed variable for all your platforms, instead of one speed variable for each platform. (Do kids these days still learn the difference between “we all had a pizza” and “we each had a pizza”?)

So, within your platform class, you can still just say “speed” by itself and reference that single value. From outside the class, since it’s public, you can say PlatformMovement.speed (or whatever the name of your platform class is) to get/set the speed for all platforms.

1 Like

Sorry for the late reply, I’ve been super busy. Thanks so much for the replies everyone. I didn’t know about singletons! I watched a tutorial on it and made one to hold a value for speed.

OK… though you don’t really need that in this case unless you want to view/set the speed in the Inspector. Otherwise, a simple static variable in your platform class would do the job.

Ah ok, thanks Joe, perhaps I’ll change to a static instead to simplify. One question, what is the exact code to alter a static-variable’s value for multiple instantiations at once from an outside class?

If your class is called PlatformMovement, and your public static variable is called speed, then from anywhere (same class or different class, it doesn’t matter), the exact code to change it is:

PlatformMovement.speed = 42;
1 Like

That seems simple enough!:slight_smile: