- Home /
change material on background
im trying to change the material of a plane at runtime based on a co routine it should be one material for 3 seconds and then the other for 3 seconds im trying to do something like this
public Material mat1;
public Material mat2;
bool material = false;
void Start () {
current = this;
GetComponent<Renderer>().material = mat1;
}
IEnumerator MyCoroutine()
{
bubbles();
yield return new WaitForSeconds(3.0f);
clouds();
yield return new WaitForSeconds(3.0f);
}
// Update is called once per frame
void Update () {
StartCoroutine(MyCoroutine());
}
void bubbles()
{
if (material == false)
{
GetComponent<Renderer>().material = mat2;
go();
material = true;
}
}
void clouds()
{
if (material == true)
{
GetComponent<Renderer>().material = mat1;
go();
material = false;
}
}
public void go()
{
pos += speed;
if (pos > 1.0f)
pos -= 1.0f;
GetComponent<Renderer>().material.mainTextureOffset = new Vector2(pos, 0);
}
im kinda new to unity and coding really but in my eyes this should work its meant to have a parallax effect which does work, and it does change material but the material kinda flickers and stutters back and forth is there something im not accounting for? also while im asking is there any way to parallax a sprite? not in the same way obviously as im using texture offset right now thanks for any and all suggestions
Answer by Halfbiscuit · Feb 06, 2016 at 11:36 AM
Your issue is you are starting a new coroutine every frame in the Update()
function. In this case you only want one coroutine.
Try moving the StartCoroutine(MyCoroutine());
call to your Start()
function then either put a while loop in your coroutine or have it call itself at the end.
okay i only just got to my computer to check this out @buFFalo94 i think your suggestion is for a gameObject array but again im new here so please correct me if im wrong, however @Halfbiscuit (cool name btw) your solution is PERFECT! so this is what i now have
`void Start () {
current = this;
GetComponent<Renderer>().material = mat1;
StartCoroutine($$anonymous$$yCoroutine());
}
IEnumerator $$anonymous$$yCoroutine()
{
bubbles();
yield return new WaitForSeconds(3.0f);
clouds();
yield return new WaitForSeconds(3.0f);
StartCoroutine($$anonymous$$yCoroutine());
}`
in fact looking at it now it is definitely changing the material smoothly and consistently howeverthe parallax effect is now not working
Answer by buFFalo94 · Feb 06, 2016 at 02:22 PM
if GetComponent().material = mat1 does not work try GetComponent().sharedmaterial= mat1;
Answer by buFFalo94 · Feb 06, 2016 at 02:22 PM
try renderer.sharedMaterial instead of renderer.material hope it help
I've just steppes away from it I'll be back on soon and update with what I did thank you for your replies