为什么我的全局变量变为零?

时间:2022-08-20 16:46:34

I'm writing a game engine with JRuby, and something goes wrong when I use a global variable. I have only these scripts:

我正在用JRuby编写一个游戏引擎,当我使用全局变量时会出现问题。我只有这些脚本:

main.rb:

main.rb的:

$CLASSPATH << "src.rb" 

require 'modules'
require 'SceneMenu'
require 'SceneMap'

$game.setScene(SceneMenu.new)

modules.rb:

modules.rb:

$game = Java::MyNamespace::Game::getInstance

module MyGame
  def self.cache 
    return $game.cache   # << ERROR OCCURS HERE
  end
end

SceneMenu.rb:

SceneMenu.rb:

class SceneMenu
  def initialize 
    @count = 0
  end
  def update
    if @count == 100
      $game.setScene(SceneMap.new)
    end
    @count += 1
  end
end

SceneMap.rb:

SceneMap.rb:

class SceneMap
  def initialize 
    @logoTexture = MyGame::cache.load("mylogo.png")
  end
end

My problem is that when I launch the game, it always is fine, but when my @count reaches 100, and SceneMap is created, an error occurs saying:

我的问题是,当我启动游戏时,总是很好,但是当我的@count达到100并且创建了SceneMap时,会出现错误:

undefined method 'cache' for nil:NilClass 

while I have called $game.setScene( ... ) just before.

我之前打过$ game.setScene(...)。

I do not modify my $game variable at all, so I don't know what happens.

我根本不修改我的$ game变量,所以我不知道会发生什么。

Does someone have an idea of what is going on?

有人知道发生了什么吗?

2 个解决方案

#1


0  

Maybe try changing the code to:

也许尝试将代码更改为:

$game = Java::MyNamespace::Game::getInstance

module MyGame
    def cache 
        return $game.cache   
    end
end

#2


0  

I have finally fixed my problem by writing:

我终于通过写作解决了我的问题:

module MyGame
  def self.game
    return Java::MyNamespace::Game::getInstance
  end
end

$game = MyGame::game

#1


0  

Maybe try changing the code to:

也许尝试将代码更改为:

$game = Java::MyNamespace::Game::getInstance

module MyGame
    def cache 
        return $game.cache   
    end
end

#2


0  

I have finally fixed my problem by writing:

我终于通过写作解决了我的问题:

module MyGame
  def self.game
    return Java::MyNamespace::Game::getInstance
  end
end

$game = MyGame::game