- Home /
One of my variables keeps resetting.
Hi, I'm trying to get this code to remember what the last randomly generated number (rand) is by assigning it to lastRand. The idea is that something different happens if the RNG gives the same number twice or more in a row. However, the lastRand variable keeps resetting after break. Am I missing something really obvious here? 'cos it sure feels like it. Thanks in advance!
void OnTriggerEnter (Collider ship)
{
Debug.Log("lastRand beginning = " + lastRand);
rand = Random.Range(1, 3);
switch (rand)
{
case 1:
{
// Next ring will be on the left
left.GetComponent<Text>().enabled = true;
StartCoroutine(killTextLeft());
Debug.Log("line 41 Rand is: " + rand);
if (lastRand != 1)
{
newPosition = (thisPosition + new Vector3(-50, 0, 50));
}
else if (lastRand == 1)
{
Debug.Log("far left");
newPosition = (thisPosition + new Vector3(-100, 0, 50));
}
Instantiate(newRing, newPosition, Quaternion.Euler(0, -45, 0));
lastRand = rand;
Debug.Log("line 54 lastRand is: " + lastRand); // lastRand is still what it should be here
return;
}
case 2:
{
//Next ring will be on the right
right.GetComponent<Text>().enabled = true;
StartCoroutine(killTextRight());
Debug.Log("line 63 lastRand is: " + rand);
if (lastRand != 2)
{
newPosition = (thisPosition + new Vector3(50, 0, 50));
}
else if (lastRand == 2)
{
newPosition = (thisPosition + new Vector3(100, 0, 50));
}
Instantiate(newRing, newPosition, Quaternion.Euler(0, 45, 0));
lastRand = rand;
Debug.Log("line 74 lastRand is: " + lastRand); // lastRand is still what it should be here
return;
}
}
}
@jamsjar there's nothing in the code you posted to provide any information as to why this happens.
Where is lastRand declared, and is it used elsewhere? If it's a class field and not used anywhere else, then on what GO is this script attached? One explanation would be that the script is attached on a prefab, which get instantiated and then destroyed, so each new instance has all values, including lastRand reset.
Anyway, you won't find the source of the problem in the code you posted.
@pako I figured it out, and it was simmilar to what you thought - lastRand was on an object within my newRing prefab, so when newRing was instantiated it wasn't remembering the lastRand on the previous object! facepalm
Thanks for replying, sorry I didn't give enough info to start with.