Referencing Player in game.oninit

Place to get help with not working mods / modding interface.
User avatar
Schorty
Fast Inserter
Fast Inserter
Posts: 185
Joined: Tue Aug 12, 2014 10:29 am
Contact:

Referencing Player in game.oninit

Post 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)
Tired of not being able to reduce the pollution? Try the Air-Filter-Mod
With this, you are able to use the pollution levels in your circuit network: Pollution detector
User avatar
L0771
Filter Inserter
Filter Inserter
Posts: 516
Joined: Tue Jan 14, 2014 1:51 pm
Contact:

Re: Referencing Player in game.oninit

Post 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.
User avatar
Schorty
Fast Inserter
Fast Inserter
Posts: 185
Joined: Tue Aug 12, 2014 10:29 am
Contact:

Re: Referencing Player in game.oninit

Post by Schorty »

It works! Thank you very much =)
Tired of not being able to reduce the pollution? Try the Air-Filter-Mod
With this, you are able to use the pollution levels in your circuit network: Pollution detector
Post Reply

Return to “Modding help”