We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Dynamic object creation
Page Index Toggle Pages: 1
Dynamic object creation (Read 438 times)
Dynamic object creation
Aug 10th, 2008, 2:52am
 
Hello. does anyone know how I could create many instances of an object in a for loop?

for example, instead of:

myObject new_object1 = new myObject();
myObject new_object2 = new myObject();
myObject new_object3 = .....

I want to do something like

String[] object_names = new String[100];

for (int i=0; i<10; i++) {
 object_names[i] = "new_object"+i;
}

for (int i=0; i<10; i++) {
 myObject object_names[i] = new myObject();
}

This array approach doesn't seem to be working, maybe I don't have the syntax quite right? I get the error 'expecting SEMI, found 'object_names' for the line inside the second for loop (myObject object_names[i] = new myObject();).

Can anyone help??

Thanks

Tom
Re: Dynamic object creation
Reply #1 - Aug 10th, 2008, 12:28pm
 
he way you do it is:

Code:
myObject[] objects=new myObject[100];
for(int i=0;i<100;i++)
{
objects[i]=new myObject();
}


You can't (easily) refer to objects by a string containing their name like you can in certain other languages.
Re: Dynamic object creation
Reply #2 - Aug 10th, 2008, 2:32pm
 
Thanks, just one more thing though...

I'm having trouble with where exactly I can use a for loop to declare the array of objects. If I use a for loop before void setup() then I get 'unexpected token: void', If I use it within setup, the objects[] array isn't recognised in'void draw()': i get the message 'no accessible field named "objects" was found in type "Temporary_506_9332".

Any suggestions
Re: Dynamic object creation
Reply #3 - Aug 10th, 2008, 4:25pm
 
Code:
myObject[] objects;  // declare objects as global variable

void setup() {
objects = new myObject[100];
for(int i=0;i<100;i++) {
objects[i] = new myObject();
}
}

void draw() {
// you can access objects here since it's a global variable
}
Re: Dynamic object creation
Reply #4 - Aug 10th, 2008, 11:58pm
 
Excellent, thanks very much
Page Index Toggle Pages: 1