Page 1 of 1

Same variable to create several entities

Posted: Sat Jul 18, 2020 9:47 am
by falsam
In this topic viewtopic.php?f=36&t=75717
Olli wrote:you erase indirectly cube mesh identifier (by reuse "mesh" variable)
Is using the same variable a bad method?

I use twice the entity variable in this code to create a plane and a cube.

Code: Select all

EnableExplicit

Global window, event, camera, Entity

InitEngine3D(#PB_Engine3D_DebugLog)
InitKeyboard()
InitSprite()

window = OpenWindow(#PB_Any, 0, 0, 1024, 768, "Test Shadow")
OpenWindowedScreen(WindowID(window),0,0,1024,768)

; Light
CreateLight(#PB_Any,RGB(255, 218, 185), 500, 1000, -1000)
WorldShadows(#PB_Shadow_Additive)

; Camera
camera = CreateCamera(#PB_Any, 0, 0, 100, 100)
MoveCamera(camera, 0, 5, 20)
CameraLookAt(camera, 0, 0, 0)

Entity = CreateEntity(-1, MeshID(CreatePlane(-1, 10, 10, 1, 1, 1, 1)), #PB_Material_None)
CreateEntityBody(Entity, #PB_Entity_StaticBody, 0, 0.1, 0.1)

Entity = CreateEntity(-1, MeshID(CreateCube(-1, 2)), #PB_Material_None, 0, 5, 0)
CreateEntityBody(Entity, #PB_Entity_BoxBody, 1, 0.1, 0.1)

; Render
While #True
  event = WindowEvent()
  
  ExamineKeyboard() 
  
  If event = #PB_Event_CloseWindow Or KeyboardPushed(#PB_Key_Escape)
    Break
  EndIf 
  
  RenderWorld()
  FlipBuffers()
Wend

Re: Same variable to create several entities

Posted: Sat Jul 18, 2020 5:47 pm
by spikey
It depends what you are doing.

If you use #PB_Any to create something, any thing in fact not just 3d objects, and subsquently dump or overwrite the return value you've lost control of the thing. This means you can no longer manipulate it and more importantly free it. You are then reliant on the built in garbage collection which takes place on the program closure to tidy up behind you.

This doesn't pose a problem in the example you present - although you have technically lost control of both the light and the plane entity because of this. But if you were creating many objects which never get released because you've lost control of them then you could theoretically create a situation in which the target machine runs out of memory.

As such I would regard this as a program bug but that is just my opinion...

Re: Same variable to create several entities

Posted: Sun Jul 19, 2020 10:34 am
by falsam
I don't think it matters if you don't want entity control. Thank you for your answer.