Page 1 of 1

Referencing Player in game.oninit

Posted: Sun Dec 21, 2014 11:50 pm
by Schorty
Hello there!


I just started modding and just finished my first attempt on a mod. On the way to this goal, I came across a problem, which some of you might have faced aswell. The forums search didn't help me much, so I'm asking here.

When I try to add some GUI-elements for example, I want them to be there for the entiry time. So I add them in the game.oninit event. At least, I tried! It simply won't work for me. Just to make sure, I'm not missing something, here is my attempt on achieving this:

# mod_directory\control.lua

Code: Select all

game.oninit(function()
  game.player.gui.top.add{type = "button", name="some_button", caption={"button_name"}}
end)
Error message will always be this one:
Unknown key:"Error while running the oninit: __test_mod__\control.lua:29: Map doesn't contain 1 player, this function can't be used"
I don't really understand why this happens, since in the base mod for example, game.player works pretty well in the game.oninit event.

Any help on this is greatly appreciated!


Greetings,
Schorty


P.S.: Just for the lolz: For now, my "solution" is this ugly piece of code:

Code: Select all

buttonsCreated = false

game.onevent(defines.events.ontick, function(event)
  if buttonsCreated == false then
    local player = game.getplayer(1)
    if player ~= nil then
      createButtons()
      buttonsCreated = true
    end
  end
end)

Re: Referencing Player in game.oninit

Posted: Mon Dec 22, 2014 1:54 am
by L0771
Use oninit only for initialize variables and compatibility with technologies/recipes and others mods.

For create gui use

Code: Select all

game.onevent(defines.events.onplayercreated, function(event)
local player = game.getplayer(event.playerindex)
--code
end)
First charge oninit, it start before create a player, the only way to use this if is you active the mod on a started map.

I try to use ontick for functions of mod, never to initialize

for debug the gui use

Code: Select all

if not game.player.gui.top.some_button then
-- add button
end
and the gui is restarted if is removed for some reason.

Re: Referencing Player in game.oninit

Posted: Mon Dec 22, 2014 11:07 am
by Schorty
It works! Thank you very much =)