using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquadsGenerator : MonoBehaviour
{
public GameObject squadPrefab;
public int numberOfSquads;
public int numberOfMembersInsquad;
private GameObject squadsParent;
private void Start()
{
squadsParent = GameObject.Find("Squads");
GenerateSquads(numberOfSquads, numberOfMembersInsquad, squadPrefab);
}
// Update is called once per frame
void Update()
{
}
public void GenerateSquads(int squadsCount,
int numberOfMembers,
GameObject squadMemberPrefab)
{
for (int i = 0; i < squadsCount; i++)
{
GameObject newSquad = new GameObject();
newSquad.name = "Squad " + i;
newSquad.tag = "Squad";
newSquad.transform.parent = squadsParent.transform;
ColorSquads(newSquad);
for (int x = 0; x < numberOfMembers; x++)
{
var go = Instantiate(squadMemberPrefab);
go.name = "Member " + x;
go.tag = "Squad Member";
go.transform.parent = newSquad.transform;
}
}
}
private void ColorSquads(GameObject squad)
{
//Fetch the Renderer from the GameObject
Renderer rend = squad.GetComponent<Renderer>();
//Set the main Color of the Material to green
rend.material.shader = Shader.Find("_Color");
rend.material.SetColor("_Color", Color.green);
//Find the Specular shader and change its Color to red
rend.material.shader = Shader.Find("Specular");
rend.material.SetColor("_SpecColor", Color.red);
}
}
But now it will color all the squads in green.
I want that it will color the first squad for example in green the next squad in red the next in green and so on. green,red,green,red....
To extend the method ColorSquads to get two colors for example Color 1, Color 2 and this will set the colors switch to color each squad once in Color 1 once in Color 2.
Screenshot of the hierarchy each Squad is empty gameobject and the squad members are child of each squad.
rend.material
. That copy won't get garbage collected automatically except during a scene load, so you might want to add a little book-keeping to keep track of when it's no longer needed and manuallyDestroy()
it. – DMGregory Nov 12 '21 at 14:48MaterialPropertyBlock
s. But I didn't want to deviate more than necessary from OPs original design. – Philipp Nov 12 '21 at 14:53foreach (Transform squadMember in squad.transform)
. – Philipp Nov 12 '21 at 14:58ColorSquad
method as I wrote it here should actually work on any gameObject with aRenderer
with a material with a_Color
property. So you could use this as-is if you moved the call to the innerLoop and passedgo
instead ofnewSquad
. – Philipp Nov 12 '21 at 15:02squadNumber % numberOfColors
. – Philipp Nov 12 '21 at 15:58