- Home /
Custom class functions - accessing one instance changes them all?
I have put the following code in a script:
class Panel {
public static var cornerPos = new Vector3[3];
function Panel(){}
function Make( x0 : float, y0 : float, z0 : float, x1 : float, y1 : float, z1 : float, x2 : float, y2 : float, z2 : float ) {
cornerPos = [ Vector3(x0,y0,z0), Vector3(x1,y1,z1), Vector3(x2,y2,z2) ];
}
}
function Blueprint() { var p = 6; panels = new Panel[p]; for (var ps=0;ps<p;ps++) { panels[ps] = new Panel(); }
panels[0].Make( 0,0,0, 0,6,0, 5,0,2 );
panels[1].Make( 0,6,0, 5,4,2, 5,0,2 );
panels[2].Make( 5,0,2, 5,4,2, 8,0,-1 );
panels[3].Make( 5,4,2, 8,5,-1, 8,0,-1 );
panels[4].Make( 8,0,-1, 8,5,-1, 14,0,1 );
panels[5].Make( 8,5,-1, 14,7,1, 14,0,1 );
}
So the Panel class has an array (length=3) of Vector3's, one for each corner of the panel. The idea of the Blueprint() function is to make 6 instances of the Panel class and then set the Panel.cornerPos[] values. 6 instances of the class are being created fine, BUT - they all have the same cornerPos[] values. I've also tried it without the Make() method thus:
panels[0].cornerPos[0] = Vector3( 0,0,0);
panels[0].cornerPos[1] = Vector3( 0,6,0);
panels[0].cornerPos[2] = Vector3( 5,0,2 );
And the result is the same - just accessing one instance sets the values for the other instances. What am I doing wrong?
Answer by Mike 3 · Aug 05, 2010 at 06:43 PM
You're using a static variable to store the data - that'll be shared between all instances of the class
If you remove static, it should work (Though seeing as it's public too, hopefully you're not using it outside the class for anything)
Perfect!
Why not use the variable outside of the class? Can I not have a line somewhere like... panels[0].cornerPos[0] = Vector3(0,0,0); ? It seems to work fine, is that not a good idea?
That's fine - I was thinking more along the lines of using it as a static with Panel.cornerPos[0] = whatever;