- Home /
Why is this C# script causing lag spikes between the game objects being cycled?,
I've written a script in C# which cycles through game objects in a scene. It stores all of the game objects in a List, shuffles them so they are randomised and then activates them and deactives them with a defined delay. For some reason, it will randomly have lag spikes between the game objects being displayed. It sporadically takes longer than the defined delay set in the script to cycle between game objects. There doesn't seem to be any rhyme or reason as to when the lag spikes occur, as far as I can tell. The script compiles and runs fine, displaying the behaviour I would expect except for this random lag. Any advice on how to optimise it so that there is no lag would be greatly appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Dolwhale : MonoBehaviour{
public List<GameObject> objects;
public int cycleCount = 10;
public float startDelay = 0.0F;
public float secsToWait = 2.0F;
// Use this for initialization
void Start() {
StartCoroutine(Cycle());
}
IEnumerator Cycle(){
yield return new WaitForSeconds(startDelay);
for (int i = 0; i < cycleCount; i++){
HelperFunctions.Shuffle (objects);
foreach (GameObject current in objects){
current.SetActive(true);
yield return new WaitForSeconds(secsToWait);
current.SetActive(false);
}
}
}
}
public static class HelperFunctions {
public static void Shuffle<T>(this IList<T> list){
int l = list.Count;
for (int i = 0; i < l; i++) {
//pick new random index
int random = i + Random.Range (0, l - i);
//swap into new spot
T newSpot = list [random];
list [random] = list [i];
list [i] = newSpot;
}
}
}
,
Answer by SlowCircuit · Jun 18, 2018 at 01:48 AM
Try putting some Debug.Log() calls at specific points that tell you what section was just completed and what Time.time currently is. That way you can see exactly what sections are having hiccups. It's also possible your lag is unrelated to the code. It could be related to the objects that you're manipulating.