- Home /
Question by
NoobCarl · Mar 20, 2021 at 11:33 AM ·
materialgetcomponentrendererforeachgetcomponentinchildren
how do I change the properties of a material that are on the children of an object on script?
This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetBehaviour : MonoBehaviour
{
[SerializeField] GameObject shatteredTarget;
[SerializeField] float breakForce;
[SerializeField] float durationDissolve = 1f;
GameObject frac;
public void DestroyTarget(Vector3 hitPos)
{
frac = Instantiate(shatteredTarget, transform.position, transform.rotation);
foreach (Rigidbody rb in frac.GetComponentsInChildren<Rigidbody>())
{
Vector3 force = (rb.transform.position - transform.position).normalized * breakForce;
rb.AddForceAtPosition(force, hitPos, ForceMode.Impulse);
Debug.Log("Force applied");
}
StartCoroutine(CutOffEffect());
Destroy(transform.parent.gameObject);
Destroy(gameObject);
}
IEnumerator CutOffEffect()
{
foreach (Renderer fracRenderer in frac.GetComponentInChildren<Renderer>())
{
float timePercent = 0f;
Debug.Log("Dissolve effect starting");
while (timePercent < 1)
{
timePercent += Time.deltaTime / durationDissolve;
fracRenderer.material.SetFloat("_Cutoff", Mathf.Lerp(0f, 1f, timePercent));
yield return null;
}
}
}
}
On the IEnumerator CutOffEffect i'm trying to change the float of a property "_Cutoff" in every children's material that are on "frac".
foreach (Renderer fracRenderer in frac.GetComponentInChildren<Renderer>())
{
float timePercent = 0f;
Debug.Log("Dissolve effect starting");
while (timePercent < 1)
{
timePercent += Time.deltaTime / durationDissolve;
fracRenderer.material.SetFloat("_Cutoff", Mathf.Lerp(0f, 1f, timePercent));
yield return null;
}
}
But on this foreach i get an error, i don't why.
Comment
Answer by rh_galaxy · Mar 21, 2021 at 05:10 PM
You cannot destroy the parent (and child objects) and expect the coroutine to continue to run on later frames. You must wait with destroy until CutOffEffect() has finished.