This site requires JavaScript, please enable it in your browser!
Greenfoot back
Ipurplish
Ipurplish wrote ...

2020/6/18

mouse null pointer exception?

Ipurplish Ipurplish

2020/6/18

#
null pointer exception at the if(mouse.getButton()==1){ line. I don't know what's wrong. can anyone help?
public void act()
    {
        MouseInfo mouse = Greenfoot.getMouseInfo();
        GreenfootSound menu=new GreenfootSound("Menu.wav");
        if(mouse.getButton()==1){
            menu.stop();
        }
    }
danpost danpost

2020/6/18

#
If the mouse is inactive on any moment in time (which actually is quite often), no MouseInfo object is created and your line 3 will set the mouse variable to null. You cannot call any methods on a null value like at line 5. So, line 5 needs to employ another condition:
if (mouse != null && mouse.getButton() == 1)
There is another issue with your code. Line 6 calls stop on a GreenfootSound instance that was never started. Each time you use the "new" keyword, you are creating a new -- distinct -- instance of an object of the type specified. You can never use that keyword to make a reference to an object that already exists.
Ipurplish Ipurplish

2020/6/18

#
how do i make a reference to an object that already exists?
danpost danpost

2020/6/18

#
Also, just on coding in general, you would not want to do anything unless you are sure you will need to. As an example:
GameOver gameOver = new GameOver();
if (score == 100)
{
    Greenfoot.setWorld(gameOver);
}
this creates a GameOver object prematurely. This code will probably be invoked on every act cycle and would create a new world every single time. However, only the one created once the score becomes 100 will actually be used. Better is this:
if (score == 100)
{
    GameOver gameOver = new GameOver();
    Greenfoot.setWorld(gameOver);
}
where it is created only after the score reaches 100.
danpost danpost

2020/6/18

#
Ipurplish wrote...
how do i make a reference to an object that already exists?
You need to first reference the object that holds the sound object in a field. It might be something like:
((MyWorld)getWorld()).bgMusic.stop();
where bgMusic is the name of the GreenfootSound field in your MyWorld class that your MyWorld object will set its music to.
Ipurplish Ipurplish

2020/6/18

#
thankyou! first time playing around with music
You need to login to post a reply.