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

2014/8/7

Issue with removing object.

gdwd4 gdwd4

2014/8/7

#
Hi, the issue that I am having is that when the object "RedTile" tries to remove the objects "Back" , "BlueTile" , "GreenTile" and "WhiteTile" it cannot find the variable "Back". The code is shown below:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class RedTile here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class RedTile extends Actor
{
    private Brick brick;
    
    public RedTile(Brick pointBrick)
    {
        brick = pointBrick;
    }
    
    /**
     * Act - do whatever the RedTile wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        if(Greenfoot.mouseClicked(this))
        {
            brick.setRed();
            
            getWorld().removeObject(Back);
            getWorld().removeObject(BlueTile);
            getWorld().removeObject(GreenTile);
            getWorld().removeObject(WhiteTile);
        }
    }    
}
Now, the object "Back" was not originally on the world but was added to the world by the "Brick" object. That code is shown below:
getWorld().addObject(new Back(this), 300, 300);
        getWorld().addObject(new RedTile(this), 208, 248);
        getWorld().addObject(new BlueTile(this), 208, 335);
        getWorld().addObject(new GreenTile(this), 394, 248);
        getWorld().addObject(new WhiteTile(this), 394, 335);
Any help would be greatly appreciated!
Super_Hippo Super_Hippo

2014/8/7

#
There is a difference between 'class' and 'object'. An object is an instance of a class. In the code at the bottom, you create an object of class 'Back' and so on. If you click an (or the) object of the class 'RedTile', you try to remove the 'objects' which you created below. You can not say "remove this class". To delete an object, you need a reference to it or you can delete every instance of the class. This probably solves the problem, too, if you don't need to separate between different e.g. BlueTiles in your world. So either use this
getWorld().removeObjects(getWorld().getObjects(Back.class);
or set a reference to the object when you create it, so you can later delete this object. Creation:
public class Worldname extends World
{
    Back back;

    public Worldname()
    {
        //super(...);
        //....
        back = new Back();
        addObject(back, 300, 300);
        //...
    }
}
Deletion:
//...
if(Greenfoot.mouseClicked(this))  
{
    Worldname w = (Worldname) getWorld();
    w.removeObject(w.back);
    //...
}
Not tested, but it should work.
You need to login to post a reply.