Reputation: 83
I am making a space themed cookie clicker sort of game for android and I have got the basic bit of clicking on a button and adding one to the main integer, in this case planets. I want to now do the thing where you buy an item that adds a certain amount of planets to the main planets integer every certain amount seconds.
I struggled with this, I tried creating a class with a method that adds an integer to the main planets integer but I could not access the main planets integer in this class.
This was the class
public class Ship {
int planetAddAmount;
int planetAddTime;
public void planetAdd()
{
planets += planetAddAmount;
//^^it does not read planets as anything
}
}
so i tried doing the getter thing (not 100% familiar with it)
public int planets;
public int planetGetter()
{
return planets;
}
but the other class still cant access the planet integer. Can someone help me make the class understand the planets integer
Upvotes: 0
Views: 102
Reputation: 456
Shouldn't this solve your problem?
public class GameState {
private int planets;
public void addPlanets(int amount)
{
this.planets += amount;
}
}
public class Ship {
private int planetsAmount;
public void addPlanets(GameState gameState)
{
gameState.addPlanets(planetsAmount);
}
}
(Edit: good point) You need to have some sort of global variable that keeps track of the number of planets. For this I used the class GameState. So in the start of your program you should make an instance of GameState. You can pass this object if you need the game state to be changed.
Your current code doesn't work since you have a variable called planets which is not declared in your class.
Upvotes: 1
Reputation: 6433
Provided this is all the related code, you haven't assigned anything to planets, in either code, which is why it doesn't read anything.
In planetGetter(), even if you do assign a value to planets, you only return the value, not the variable name.
Upvotes: 5
Reputation: 9261
Make the planets as an instance field so multiple methods can have access to it
Upvotes: 0