Performance Issue on Update
I'm having trouble figuring this out. I'm trying to slow the speed of an object depending on another script [the score]. Problem is that performance is really bad, and doing a Coroutine isn't very practical since checking the score every X amount of time - might actually not work all the time.. I.E. What's the chance of hitting the score on the 5th second that the Coroutine is ran?
Here is my script:
public class MovePlank : MonoBehaviour
{
public float plankMover = -2.0f;
ScoreTracker checkScore;
public float amplitudeX = 10.0f;
public float amplitudeY = 5.0f;
public float omegaX = 1.0f;
public float omegaY = 5.0f;
float index;
float checkScoreTime = 5.0f;
bool checkLevelOne = false;
// Use this for initialization
void Start ()
{
checkScore = GetComponent<ScoreTracker>();
}
// Update is called once per frame
void Update ()
{
StartCoroutine(WaitToCheckScore(checkScoreTime));
transform.Translate(plankMover * Time.deltaTime, 0f, 0f);
if (checkLevelOne)
{
/* index += Time.deltaTime / plankMover; //this changes the X speed as it technically slows down time. Increase paintSpeed to slow it down further.
float x = amplitudeX * Mathf.Cos(omegaX * index); //amplitude X is the X value as where it'll generate while omegaX shouldn't really be touched.
float y = amplitudeY * Mathf.Sin(omegaY * index); // amplitude Y is the Y value as where it'll generate and omegaY is how many times it goes up and down.
transform.localPosition = new Vector3(x, y, 0); */
transform.Translate(plankMover / 2 * Time.deltaTime, 0f, 0f);
}
}
IEnumerator WaitToCheckScore (float checkScoreTime)
{
yield return new WaitForSeconds(checkScoreTime);
if (checkScore.levelOne)
{
checkLevelOne = true;
}
}
}
Suggestions?
Answer by Chris333 · Jun 03, 2016 at 08:03 PM
Hi,
your performance problems are maybe occuring because you are starting each frame a new coroutine.
Try to start the coroutine only if its not already running. Something like that:
if(!running)
{
StartCoroutine(WaitToCheckScore(checkScoreTime));
}
IEnumerator WaitToCheckScore (float checkScoreTime)
{
running = true
yield return new WaitForSeconds(checkScoreTime);
running = false
if (checkScore.levelOne)
{
checkLevelOne = true;
}
}
@Chris333 I didn't really want to use a Coroutine though. It was just the only way I can think of that limits in checking if something is true and not bog down the performance. Is this the only way, by using a coroutine?
@Chris333 Alright, so I do need to use a coroutine. Thank you very much for your help!
Your answer
![](https://koobas.hobune.stream/wayback/20220612082221im_/https://answers.unity.com/themes/thub/images/avi.jpg)