keeping a list unique to an instance of an object

Monkey Forums/Monkey Programming/keeping a list unique to an instance of an object

Paul - Taiphoz(Posted 2012) [#1]
I have a class which has a field called points, which is a list.

How would I go about making that list unique to each instance or object created from the class, at the moment the ponts list is hold all points from the class and not just the points from the instance or object Im dealing with at the time.


Jesse(Posted 2012) [#2]
Put the list outside of the class as a local, global or a field. I usually keep a field on the player for the player's bullet and a global for all of the enemies and use the same class for all of the bullets just with different images.


invaderJim(Posted 2012) [#3]
Unless you declare the list as Global, it should be unique to each instance of the class. What does your code look like?


Paul - Taiphoz(Posted 2012) [#4]
see, thats what I was expecting to happen..

Class cShape extends cVector2D

	'summary:A list that holds cPoint objects, which make up the shape.
	Field points:List<cPoint>
	
	'summary:Counter to hold the number of points, this probably isnt needed.	
	Field count:int 
	
	'summary:the centre of the shape, for rotation.
	Field handle:cPoint
	
	#Rem
	summary: New
	Create a new shape and initilize its point list.
	#End
	Method new(newshape:List<cPoint>)
		Self.points = new List<cPoint>
		Self.points = newshape	
	End	

...
	Method Move(nx:float,ny:float)
		
		For Local tp:cPoint = eachin self.points			
			tp.SetX = tp.GetX-Self.handle.GetX
			tp.SetY = tp.GetY-Self.handle.GetY	
		Next

		Self.handle.SetX=nx
		Self.handle.SetY=ny

		For Local tp:cPoint = eachin self.points			
			tp.SetX = tp.GetX+nx
			tp.SetY = tp.GetY+ny
		Next

	End


So I was expecting it to only move the current object, but its actually moving all points global to the class, and not just those for the object.


Gerry Quinn(Posted 2012) [#5]
Yes, what invaderJim says should be the default. For example:



...should have a separate list in each class instance containing points that have been created by that instance.


Gerry Quinn(Posted 2012) [#6]
Ah, this is where you are going wrong:

	Method new(newshape:List<cPoint>)
		Self.points = new List<cPoint>
		Self.points = newshape	
	End	


Instead of adding points to the points field, you are setting the points field to point to newshape.

Try this:

	Method New(newshape:List<cPoint>)
		points = New List<cPoint>
		For Local pt:cPoint = Eachin newshape
			points.AddLast( pt )
		Next
	End	


Note that the above still does not copy the actual points themselves, which may or may not be your intention. For example if you initialised two cShapes with the same instance of newshape, they would have the same points.


Paul - Taiphoz(Posted 2012) [#7]
Ah it was the way I was passing the list's around, when I switched to actually populating the list from within the class it solved the problem..