Home > Software engineering >  alternate two methods for x seconds, with a pause of y seconds
alternate two methods for x seconds, with a pause of y seconds

Time:12-27

I have two methods, PaintRed and PaintDefault. I would like this two methods to alternate for x seconds, with a pause of y seconds when the variable _gm._playerHited is equal true. I want to get a red colour flashing effect on my model.

I can't make head nor tail of this. I probably need to use coroutine, but I haven't come up with a solution to my problem yet.

using UnityEngine;
public class PaintModel : MonoBehaviour {
GameObject _player;
GameObject _model;
GameManagerScript _gm;

Color32[] objColor = new Color32[9];

private void Start() {
    _player = GameObject.FindGameObjectWithTag("Player");
    _model = GameObject.Find("Model");
    _gm = GameObject.FindGameObjectWithTag("GM").GetComponent<GameManagerScript>();
    GetColors();
}

private void Update() {
    if (_gm._playerHited) {
    }
}

void PaintRed() {
    for (int i = 0; i < _model.GetComponent<SkinnedMeshRenderer>().materials.Length; i  ) {
        _model.GetComponent<SkinnedMeshRenderer>().materials[i].color = Color.red;
    }
}
void PaintDefault() {

    for (int i = 0; i < _model.GetComponent<SkinnedMeshRenderer>().materials.Length; i  ) {
        _model.GetComponent<SkinnedMeshRenderer>().materials[i].color = objColor[i];
    }
}
void GetColors() {
    for (int i = 0; i < _model.GetComponent<SkinnedMeshRenderer>().materials.Length; i  ) {
        objColor[i] = _model.GetComponent<SkinnedMeshRenderer>().materials[i].color;
    }
}

}

CodePudding user response:

Something along these lines?

public void StartFlash() => StartCoroutine(EFlash());
private IEnumerator EFlash()
{
    float startTime = Time.time;

    bool b = false;
    while(startTime   DURATION > Time.time)
    {
        b = !b;

        if (b) PaintRed();
        else PaintDefault();
        yield return new WaitForSeconds(FLASH_SPEED);
        
    }
}

you could call the StartFlash method when the player got hit eg checking in update if the bool has changed *(if you do it this way you want to be sure that you have the bool active for only one frame otherwise it would call the method multiple times)

OR

you could create an event on your gm and subscribe to it from your current script (which would be the cleaner way)

  • Related