Puzzled
TheTinman
Member Posts: 74
Why does this script fire every time I open a chest? Shouldn't it not fire if the 5 creatures are spawned in?
void main() { int i ; while (i <= 5) { CreateObject(OBJECT_TYPE_CREATURE, "res_ref", GetLocation(OBJECT_SELF)); ++i; } }
0
Comments
So, every time you call the script, since you don't give i a value, it defaults to 0, and another set of creatures is created.
You will actually get 6 each time, as you create another one while i in the range 0-5.
What you need is a local variable, which does retain its value as long as the object exists:
Notice that i must be reduced by 1 before storing it on the local variable, because it will have the value 6 at the end of the loop.
In this case, I've saved the number of creatures created on the local variable, to illustrate how that's done, but you could achieve the same thing more simply with a local variable called "Triggered" which is set to TRUE when the chest is first opened.
I was getting 5 each time though.
I thought i++: gets the element and then increments it. (example: 0 1 2 3 4)
And ++i: increments i and then returns the element. (example: 1 2 3 4 5)
If you were getting 5 creatures, I must be missing something, but I'm reading the original code like this:
i=0 create creature #1 and set i = 1
i=1 create creature #2 and set i = 2
i=2 create creature #3 and set i = 3
...
i=5 create creature #6 and set i = 6
i=6 stop because 6 is not <= 5
So it stops at i =4 returns 5 because i =5 would return 6?
As expected, it produces 6, not 5.
Thanks again Proleric.