Hey everyone,
I am having some problems with lag whenever I activate a script.
I have a jackhammer in game, then I have a GUI button firing off an “autojack” script.
Everything works as expected. However, there is about a three second lag before the jackhammer starts jacking. Its not a lag in the GUI system. I have tested this by manually activating the script in the inspector during gameplay, and there is still a 3 second lag. So I know there is something wrong with my code. Am I even going about this the right way? Its a rigidbody, so I am putting it in fixedupdate. But I dont know if I’m actually doing this right. I’m new to c#, so any advice would be awesome! Thanks
using UnityEngine;
using System.Collections;
public class AutoJack : MonoBehaviour
{
public float thrust;
public Rigidbody rb;
void FixedUpdate()
{
StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine()
{
yield return new WaitForSeconds(.1f);
JackDown();
yield return new WaitForSeconds(1);
JackUp();
yield return null;
}
void JackUp ()
{
rb.AddForce(Vector3.up * thrust);
}
void JackDown ()
{
rb.AddForce(-Vector3.up * thrust);
}
}
Since you start Coroutine in FixedUpdate. There will be hundreds of corutines running within seconds of the script activation. Thus eating your processing power. Try this instead.
void Start()
{
StartCoroutine(MyCoroutine());
}
IEnumerator MyCoroutine()
{
yield return new WaitForSeconds(.1f);
JackDown();
yield return new WaitForSeconds(1);
JackUp();
yield return new WaitForSeconds(timeWhichYouWantToGiveHammerToGoUP);
StartCoroutine(MyCoroutine());
}
This code will run only one coroutine at a time continuously.
I dont mean to be so dull, but you might need a better computer, If you are spawning in the same thing multiple times and it laggs that means you need more ram or a faster computer. You might need to make the thing your spawning in a bid less detailed, if its particles you need less particles, if its a model, give the model less proxies…