Sendmessage performance

Hi Guys,

I’m relatively new to Unity development. I’ve got a bit of experience with c# (mostly visual c# / windows programs) and have been trying to write my own RTS game, mostly as a learning experience.

I’m currently just trying to build standard RTS controls. One of which is selecting all units of a certain type on screen when you hold the ctrl button. So, this is from my Update section:

if(Input.GetKey ("left ctrl"))					
{
	Plane[] planes = GeometryUtility.CalculateFrustumPlanes (camera);	
	foreach (GameObject g in _allunits)
	{
		if(GeometryUtility.TestPlanesAABB(planes, g.collider.bounds))
		{
			g.GetComponent ("unit").SendMessage ("UnitSelected",true);
			_selectedunits.Add (g);
		}
	}
}

Now, I only have 133 units in _allunits (all the same type, so I’m not checking that in the code yet) and while the above works, when I zoom out a bit to see all the units and try it, there’s almost a second delay before anything happens. During this time, any animation / camera movement freezes.

I initially thought that looping through _allunits was causing the problem, but it appears to be the send message / getcomponent.

Can anyone suggest something that may help me out here? I’ve tried:

(unit)g.getcomponent(“unit”).UnitSelected(true);

and a couple of variations, but they all seem to cause the same amount of delay.

Cheers
Ross

Are you absolutely sure the lag isn’t from doing hundreds of debug messages in a single frame? Debug is very often the cause of significant lag like you describe. Doing the I/O to write to the editor log file does take a relatively significant amount of time.

I don’t know if this will boost performance, but you could try:

(unit)g.GetComponent<unit>().UnitSelected(true);

If that doesn’t work, I’d look through any performance snags in the UnitSelected() function itself. This may require digging.

Why are you storing an array of GameObject if you need to GetComponent every frame? You’ll probably get a pretty massive speed boost if you maintain an array of the component rather than the GameObjects.

Also, SendMessage is pretty slow, and by doing the GetComponent you’ve already thrown away the “usefulness” of SendMessage anyway. Just call the function directly. I’ve also heard the Generic version is faster (no string overheads).

UnitType unitType = unitGameObject.GetComponent<UnitType>();

Also, did you consider adding some code to make it only run once? (I assume its doing it every frame you have ctrl down, since there seems to be no code to implement “fire-once”)