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

2017/10/5

How to allow only one instance of an object

JamesLaa JamesLaa

2017/10/5

#
I am making a game, and don't want someone to be able to add another instance of an object. How would I do this?
Super_Hippo Super_Hippo

2017/10/5

#
You could remove it instantly.
protected void addedToWorld(World w)
{
    if (w.getObjects(ClassName.class).size() > 1)
    {
        w.removeObject(this);
    }
}
EduandErnst EduandErnst

2017/10/6

#
Or you just create a Singleton...
class Singleton {
	private static Singleton instance;
	private Singleton(){}
	
	public static Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
	}
}
Super_Hippo Super_Hippo

2017/10/6

#
Your getInstance method is missing a 'return instance;'.
You need to login to post a reply.