Night.owl
Night.owl

Reputation: 121

Slowly fade in the opacity of a particle system

I am trying to write some code that slowly fades in the opacity of the particles when the player reaches at certain position.

The particle alpha value is changed when the player reaches the postion but it doesn't slowly fade, it just suddenly changes.

I am new to programming so I was wondering if I missing anything blatantly obvious. Thanks!

public class IncreaseFog : MonoBehaviour {

    Renderer rend;
    GameObject character; 
    float valToBeLerpedFrom = 9f;
    float tParam = 0f;
    float speed = 0.01f; 
    float characterPosition;
    Color c;    

    void Start () {
        rend = GetComponent<Renderer>();
        character = GameObject.Find("CHARACTER");
    }

    void Update() {
        characterPosition = character.transform.position.x;
        if(characterPosition >= 190f) {
            StartCoroutine(increaseFog());
        }
    }

    IEnumerator increaseFog()
    {
        tParam = 0f;
        while (tParam < 1)
        {
            tParam +=  Time.deltaTime;  
            valToBeLerpedFrom = Mathf.Lerp(0f, 0.9f, tParam);
             c = rend.material.GetColor("_TintColor");
            c.a = (valToBeLerpedFrom);
            rend.material.SetColor("_TintColor", c);
        }
        rend.material.SetColor("_TintColor", c);
        yield return valToBeLerpedFrom;
    }
}

Upvotes: 0

Views: 2523

Answers (2)

Night.owl
Night.owl

Reputation: 121

I fixed this by using a box collider set as a trigger that calls the coroutine.

(thanks for the help)

Upvotes: 0

Slubberdegullion
Slubberdegullion

Reputation: 159

It's because you have a while loop in it...you need to only execute it once each frame. As it stands now, your code won't complete until alpha is 0.9, so you never see the transition.

Upvotes: 2

Related Questions