wurstscript / WurstStdlib2

WurstScript Standard Library Version 2
Apache License 2.0
55 stars 53 forks source link

`EventListener.add(u, EVENT_PLAYER_UNIT_SELECTED)` does not work in init block? #433

Open peawyoyoyin opened 9 months ago

peawyoyoyin commented 9 months ago

Hello wurstscript maintainers. I'm new to wurstscript and just fiddling around at the moment. I am trying to use ClosureEvents to trigger some actions when a specific unit is selected. The trigger is active immediately upon map initialization.

I noticed that EventListener.add(u, EVENT_PLAYER_UNIT_SELECTED) does not work if the code is not wrapped under doAfter(0.5). Is this intended? Even in the Wurst item shop demo there is doAfter(0.5) for seemingly no reason.

I am completely okay with adding 0.5 second delay to the initialization. However, I could not find this behavior documented anywhere in wurstscript docs. If this is intended or caused by some limitations, then it should be in the docs. Please let me know, I am willing to help update the docs if that is better.

Simple steps to reproduce:

  1. Clone repo https://github.com/Frotty/wurst-item-shop/tree/main & use wurst setup jar to install dependencies
  2. Comment out doAfter(0.5) in ItemShopTest.wurst
  3. Run the map
  4. Select paladin

We can no longer see "set target hero2" logged as expected.

Frotty commented 9 months ago

Hey, welcome to your Wurst journey 👋

EventListener in fact works fine at map init, which you can test with this sample code:

init
    createUnit('hfoo')
    EventListener.add(EVENT_PLAYER_UNIT_SELECTED) ->
        print("selected " + GetTriggerUnit().getName())

The reason for the timer in the item shop is that framehandles (UI components) cannot be created at map init,

Hope this helps. Consider joining discord/matrix if you require further assistance.

peawyoyoyin commented 9 months ago

@Frotty I noticed that as well, EventListener.add(EVENT_PLAYER_UNIT_SELECTED) (without the unit argument) works in map init, but the one with the unit argument (EventListener.add(u, EVENT_PLAYER_UNIT_SELECTED)) does not seem to work outside doAfter(0.5).

Consider below init block, selecting paladin does not print out "set target hero2"

init
  let bm1 = createUnit(players[0], UnitIds.bloodmage, ZERO2, angle(0))
  let bag = createUnit(players[0], UnitIds.paladin, ZERO2, angle(0))

  EventListener.add(bm1, EVENT_PLAYER_UNIT_SELECTED) ->
    print("set target hero1")

  EventListener.add(bag, EVENT_PLAYER_UNIT_SELECTED) ->
    print("set target hero2")
Frotty commented 9 months ago

Oh, that's correct due to the indexing not happening at map init, thanks for the report.