Skip to content

Puzzled

TheTinmanTheTinman Member Posts: 74
edited November 2023 in Builders - Scripting
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;
 }


 }

Comments

  • ProlericProleric Member Posts: 1,316
    edited November 2023
    The problem is that normal variables don't retain their value between script calls.

    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:
    void main()
    {
         int i  = GetLocalInt(OBJECT_SELF, "CreatureCount") ;
    
         while (++i <= 5)
          {
            CreateObject(OBJECT_TYPE_CREATURE, "res_ref", GetLocation(OBJECT_SELF));
          }
    
        SetLocalInt(OBJECT_SELF, "CreatureCount",  --i) ;
     }
    

    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.
  • TheTinmanTheTinman Member Posts: 74
    edited November 2023
    Thank you for that explanation Proleric. And the script you gave works perfectly.
    You will actually get 6 each time, as you create another one while i in the range 0-5.

    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)
    Post edited by TheTinman on
  • ProlericProleric Member Posts: 1,316
    Indeed, ++i increments i then returns the new value.

    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
  • TheTinmanTheTinman Member Posts: 74
    Maybe it reads the return value and runs if that return value is <=5?

    So it stops at i =4 returns 5 because i =5 would return 6?
  • ProlericProleric Member Posts: 1,316
    I ran your original script with the resref nw_waitress.

    As expected, it produces 6, not 5.
  • TheTinmanTheTinman Member Posts: 74
    Ok. I went back and double checked my script. When I typed it in here, I messed up. Line 4 should be
    int i = 1;
    
    My bad. :#

    Thanks again Proleric.
Sign In or Register to comment.