I have created a Toggle with Unity UI and added a script to it.
So the point is, that my game instantiated a number of objects with a specific tag. I want to find them and toggle on/off their mesh renderer.
I have come so far with SetActive. However, it hides the object completely and there is a problem with unhiding it. Will be happy to receive any help!
public class ToggleRaycast : MonoBehaviour
{
public Toggle m_Toggle;
public void OnMouseDown()
{
if (m_Toggle.isOn)
{
GameObject[] raycasters2 = GameObject.FindGameObjectsWithTag("Raycaster");
foreach (GameObject raycaster2 in raycasters2)
{
raycaster2.SetActive(true);
}
}
else
{
GameObject[] raycasters2 = GameObject.FindGameObjectsWithTag("Raycaster");
foreach (GameObject raycaster2 in raycasters2)
{
raycaster2.SetActive(false);
}
}
}
}
var renderers = GameObject.FindGameObjectsWithTag("Raycaster")
.SelectMany(go => go.GetComponentsInChildren<MeshRenderer>());
foreach(var renderer in renderers ) {
renderer.enabled = false;
}
Like that? You can Get Renderers from children but note it will also include TrailRenderer, ParticleSystemRedenrer etc. There is no explicit base class for MeshRenderer and SkinnedMeshRenderer so you might need to handle both cases like that feg.
var renderers = GameObject.FindGameObjectsWithTag( "Raycaster" )
.SelectMany( go => go.GetComponentsInChildren<Renderer>() )
.Where(renderer => renderer is SkinnedMeshRenderer || renderer is MeshRenderer);
Also note that FindGameObjectsWithTag and GetComponentsInChildren and very expensive operations and you should avoid using them during gameplay You should make field for renderers and initialize them once in Start or Awake
private IEnumerable<Renderer> _renderers;
void Start(){
_renderers = GameObject.FindGameObjectsWithTag("Raycaster")
.SelectMany(go => go.GetComponentsInChildren<MeshRenderer>());
}