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

2017/12/11

Sharing variables through Actors

XD-69 XD-69

2017/12/11

#
I have a button, when you click adds 1 to score displayed at top of screen I have another button that i want to add 10 to the increase of the main button (which increases score) here is my code how would i make this happen Main click.
import greenfoot.*;

/**
 * Write a description of class BlueClick here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class BlueClick extends Actor
{
    private int var = 0;
    private int add = 1;
    /**
     * Act - do whatever the BlueClick wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        getWorld().showText("Score: " +var, 100, 40);
        if (Greenfoot.mouseClicked(this))
        {
            var = var + add;
        }
    }    
}
My increase main clicker button code
import greenfoot.*;

/**
 * Write a description of class plus_ten_upgrade here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class plus_ten_upgrade extends Actor
{
    
    /**
     * Act - do whatever the plus_ten_upgrade wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        getWorld().showText("+10", 50, 82);
        if (Greenfoot.mouseClicked(this))
        {
            
        }
    }
}
    

Thanks
danpost danpost

2017/12/11

#
You can add a public method that adjusts the value of 'add' by a given amount to the BlueClick class:
public void adjustAdd(int adjustment)
{
    add += adjustment;
}
Now, a plus_ten_upgrade object need to get a reference to the BlueClick object in your world so that it can perform its function. To get a reference and call the method:
((BlueClick)getWorld().getObjects(BlueClick.class).get(0)).adjustAdd(10);
XD-69 XD-69

2017/12/11

#
Where do i put the ((BlueClick)..............get(0)).adjustAdd(10); in the add 10 code?
danpost danpost

2017/12/11

#
XD-69 wrote...
Where do i put the ((BlueClick)..............get(0)).adjustAdd(10); in the add 10 code?
Line 21 of plus_ten_upgrade class.
XD-69 XD-69

2017/12/11

#
Awesome thanks alot.
You need to login to post a reply.