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

2016/3/6

I need help with string variables + addObject

Boogabacon Boogabacon

2016/3/6

#
1
2
3
4
5
6
U1 = "Upgrade" + Greenfoot.getRandomNumber(2);
           U2 = "Upgrade" + Greenfoot.getRandomNumber(2);
           U3 = "Upgrade" + Greenfoot.getRandomNumber(2);
           //addObject(new U1goesHere(),300,200);
           //addObject(new U2goesHere(),400,200);
           //addObject(new U13goesHere(),500,200);
In short I to make a string that is equivalent to a class name and then have that class name be used to make an new object that creates the class made out of the string variable in three different slots. e.g UPGRADE 1 UPGRADE 2 UPGRADE 3 And each upgrade slot can be different depending on the string variable
danpost danpost

2016/3/6

#
You cannot change a String type object into a Class type object. All you can do is compare a String object with the string representation of a class name. With your first three lines, you will end up with references to three String object that are each either "Upgrade0" or "Upgrade1" stored in the three variables U1, U2 and U3. Presuming that these are correct as far as what you are wanting, then you can do something like the following:
1
2
3
4
5
6
7
8
for (int i=0; i<3; i++)
{
    Actor u1 = new Upgrade1();
    Actor u2 = new Upgrade2();
    Actor[] actors = { u1, u2 };
    int index = Greenfoot.getRandomNumber(actors.length);
    addObject(actors[index], 300+100*i, 200);
}
With this you can create any number of actors (adding to lines 3 and 4), place them in the array (line 5) and add a randomly chosen one into the world (line 7).
Boogabacon Boogabacon

2016/3/6

#
Thanks for the help, This code is much easier to use than huge If statements!
danpost danpost

2016/3/7

#
Boogabacon wrote...
Thanks for the help, This code is much easier to use than huge If statements!
Usually, if you find yourself using "huge If statements", there will be a much easier, more simple way.
You need to login to post a reply.