Proper approach to modifying multiple objects

What is the easiest and most efficient (in regards to a mobile game) way to modify multiple gameobjects?

For example, let’s say I’m making a Pac Man game, and if the player collects a certain power-up, all the ghosts in the scene would flash for 30 seconds.

Now one approach would be to do a Find command on each ghost, then also GetComponent to access their MeshRenderer (to enable / disable it).

But I’m aware Find and GetComponent are quite slow commands… So what I’d usually do to maximize efficiency would be to execute these only once during Startup and cache them into variables. But aside from the fact that these ghosts are instantiated on the fly, if there’s a large number of them, I’d end up with a script that looked something like this:

var ghost1Mesh : MeshRenderer;
var ghost2Mesh : MeshRenderer;
var ghost3Mesh : MeshRenderer;
var ghost4Mesh : MeshRenderer;
var ghost5Mesh : MeshRenderer;
var ghost6Mesh : MeshRenderer;

function Start ()
{
    ghost1Mesh = GameObject.Find("ghost1").GetComponent(MeshRenderer);
    ghost2Mesh = GameObject.Find("ghost2").GetComponent(MeshRenderer);
    ghost3Mesh = GameObject.Find("ghost3").GetComponent(MeshRenderer);
    ghost4Mesh = GameObject.Find("ghost4").GetComponent(MeshRenderer);
    ghost5Mesh = GameObject.Find("ghost5").GetComponent(MeshRenderer);
    ghost6Mesh = GameObject.Find("ghost6").GetComponent(MeshRenderer);
}

I suppose it would make sense to use an array at this point, would that be right? Is there anything else I can do to make this process more efficient, say if I had 100 enemies for example?

Any input would be appreciated before I head in any particular wrong direction. I’m still quite new to Unity and would like to avoid picking up any bad habits at every opportunity. :slight_smile:

There’s a simpler way to do that: have a static boolean flag - flash, for instance - in the player script, and make it alternate true/false when blinking the ghosts, and read it in the ghost script to control the effect - like this:

Player script (say, PlayerScript.js):

// call FlashGhosts(30) to make all ghosts flash for 30 seconds

static var flash: boolean = false; // disable ghost renderers when true
static var flashing: boolean = false; // is true while flashing 

function FlashGhosts(time: float){
  if (flashing) return; // abort FlashGhosts calls when already flashing
  flashing = true; // signals "I'm flashing now"
  for (var t: float = 0; t < time; t += 0.5){
    flash = true;
    yield WaitForSeconds(0.25);
    flash = false;
    yield WaitForSeconds(0.25);
  }
  flashing = false; // ended flashing
}

In the ghost script:

private var rendr: Renderer;

function Start(){
  rendr = renderer;
}

function Update(){
  rendr.enabled = !PlayerScript.flash; // ghost invisible when flash is true
  ...
}