For loop resetting itself, but needs to stop

Hi, using C#, my problem is when my code runs I’m supposed to turn three random objects from an array of objects called ‘distractors’ every third second, but somehow it turns a lot more objects. The first for loop is run multiple times instead of just the one time (about 35 times). It is supposed to go from 0 to two and then stop, but it just starts over.

I honostly do not see why this problem is happening, so any help is appreciated. Or if you have a better way to turn three random objects from a list of objects that would also be good.

void Update () {
		
		timeLeft -= Time.deltaTime;
		if(timeLeft < 0)
		{
			for(int k = 0; k < 3; k++)
			{
				tmp[k] = Random.Range(0, distractors.Length);
				Debug.Log(tmp[k] + " start | k: " + k);
				for(int j = 1; j < k; j++)
				{
					if(k > 0)
					{
						if(tmp[k] == tmp[k-j])
						{
							tmp[k] = Random.Range(0, distractors.Length);
							//Debug.Log(tmp[k] + " new | j:" + j);
							j = 0;
						}
					}
				}
				//Debug.Log(tmp[k]);
				distractors[tmp[k]].transform.Rotate(Vector3.forward * z); 
			}
			timeLeft = 3.0f;
		}

		//Debug.Log(timeLeft);
	}

If you’re only doing 3 objects, it makes complete sense to just brute force it.
Declare 3 variables instead of one and do the work 3 time. Just remove the loops completely. You’re not doing so many things that it becomes cumbersome to do it manually.

“Calling every third second” is a great definition for a Coroutine :slight_smile:
for a start:

IEnunmerator DistractedLogic()
{
    yield return new WaitForSeconds(3);
    // your logic here
}

and launch it at start function
StartCoroutine(DistractedLogic());

So, get three unique random values from an array is complex task.
For a start you may get three unique random indexes

List<int> randomIndexes = new List<int>();
int length = myCollection.Length;
int count = 3;
while (randomIndexes.Count < count)
{
    int random = Random.Range(0, length -1);
    if (!randomIndexes.Contains(random))
        randomIndexes.Add(random);
}

may be not the best approach, but it’ll did the trick.

Second step: get objects by this indexes

List<MyObjects> myObjects = new List<MyObjects>();
foreach(int i in randomIndexes)
{
    myObjects.Add(myCollection*);*

}
okay. If you have collection myCollection this code will give you myObjects collection with three random objects from myCollection.

Hope this’ll help
And excuse me for my terrible english :slight_smile: