aspose file tools*
The moose likes Beginning Java and the fly likes How to make enemy only spawn once? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to make enemy only spawn once?" Watch "How to make enemy only spawn once?" New topic
Author

How to make enemy only spawn once?

Natasha Morehouse
Greenhorn

Joined: Nov 26, 2012
Posts: 5
I am making a java game and I need to only spawn the boss once, but I am not sure how to do this.

Here is the code I have to spawn the boss:

else if (level==5)
{
double xPosition = random(0, pfWidth());
new EnemyBoss(xPosition, 100.0);
}
Manuel Petermann
Ranch Hand

Joined: Jul 19, 2011
Posts: 175

I think we might need a bit more context to help you.
If your code does what i think it does (and whithout having a look at the constructor of the EnemyBoss i cant be sure) your mistakes is not within those lines.


Please correct my English.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39435
    
  28
Look up the singleton pattern. People used to think singletons were really good things, but opinion has changed and some people say singletons are evil. It might be appropriate to make your boss a singleton. That would mean you can get as many references to the boss object as you like; they will all point to the same object.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8008
    
  22

Natasha Morehouse wrote:Here is the code I have to spawn the boss:

Which looks like it will spawn a boss (whatever that means) whenever you reach level 5. I'm not quite sure if I agree with Campbell's advice about making it a singleton (although I definitely agree with him that they're worth knowing about), but you do need to record somewhere that you've already spawned a boss.
Then your code might look something like:Winston

Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39435
    
  28
Winston Gutkowski wrote: . . . I'm not quite sure if I agree with Campbell's advice about making it a singleton . . .
Nor am I. I was offering it as a suggestion rather than advice.
An alternative is to have a static count variable in the Boss class; you only instantiate the class if it is 0. If you are multi‑threading, that method can allow several Boss objects to exist, if the constructor is accessed simultaneously by several threads. Again just a suggestion, rather than advice.
 
Don't get me started about those stupid light bulbs.
 
subject: How to make enemy only spawn once?