Batch drawcalls of GameObjects with a script attached?

Hi all,

I have a hexagonal grid that is procedurally generated at runtime, and currently it has between 100-300 draw calls depending on the map size, and it batches most - if not all - of the related tiles.

I am using GameObject.Instantiate to create these.

My issue is that as soon as I attach a script to the hex tile prefab (for functionality like OnMouseEnter, Input.MouseButtonDown etc… ) it stops batching them and increases the draw calls well into the thousands.

Any clues how to get around this?

I thought of simply creating a script that interacted with the hex grids, but was attached to another game object - but this seems inelegant. Is this really the only solution?

Here is the code;

foreach (Object_System.shell.tile _tile in _shell.tileList) {

		GameObject tile = (GameObject)Instantiate(_tilePrefab);
		Interface _script = (Interface)tile.GetComponent("Interface");
		Manager_Interface _interfaceManager = (Manager_Interface)this.GetComponent("Manager_Interface");
		_script._tileInstance = _tile;
		tile.tag = "SystemMap_Tile";
		tile.transform.position = _tile.position;
		tile.transform.parent = shell.transform;

And the a snippet of code from the script attached to the GameObject;

void Update () {

		// When mouse enters, start highlighting the tile
		if (OnEnter == true) {

			colorEnd = colorOnEnter;
			colorNow = renderer.material.color;
			colorEnd.a = Opacity;
			Duration = OnEnterDuration;
			float lerp = Mathf.PingPong (Time.time, Duration) / Duration;
			renderer.material.color = Color.Lerp (colorNow, colorEnd, lerp);

		}

You need to write your own shader to shade your hexes. As I believe was pointed in the comments, as soon as you do renderer.material = anything you have broken batching.

What you need to do is shade the hexes based on “something else” apart from the material’s color: probably the best thing would be the vertex colours of the model which you can change without breaking batching.

You could of course go the whole hog and guarantee 1 draw call by drawing all of the hexes as part of a single mesh. Your hex scripts could be used to add the necessary points to the mesh - but that is a bit more advanced but ideal in these cases.