A class variable error with Actor

Hi.
I have here a code, from a locally defined actor in a python class.

from direct.showbase.ShowBase import ShowBase
from direct.actor.Actor import Actor

base = ShowBase()

class ejemplo:
    def __init__(self):

        mundo = base.loader.loadModel("environment")		
        mundo.reparentTo(base.render)
        mundo.setScale(1)
		
        panda = Actor("models/panda-model",{"caminar": "models/panda-walk4"})
        panda.reparentTo(base.render)		
        panda.setScale(0.05,0.05,0.05)
		
        panda.loop("caminar")

clase = ejemplo()
base.run()

The problem is that when you run, the animation of the model does not play.

The problem can be corrected by changing the “panda” variable to the “self.panda” attribute and the problem would be solved.

from direct.showbase.ShowBase import ShowBase
from direct.actor.Actor import Actor

base = ShowBase()

class ejemplo:
    def __init__(self):

        mundo = base.loader.loadModel("environment")		
        mundo.reparentTo(base.render)
        mundo.setScale(1)
		
        self.panda = Actor("models/panda-model",{"caminar": "models/panda-walk4"})
        self.panda.reparentTo(base.render)		
        self.panda.setScale(0.05,0.05,0.05)
		
        self.panda.loop("caminar")

clase = ejemplo()
base.run()

Someone with knowledge, would like to explain why that happens, I do not understand :thinking:.

thanks greetings.

I think since there’s no reference to the panda variable outside of the class, it gets garbage collected after the __init__ function has completed. But this is just an assumption.

I believe that that’s correct, and that it’s a known quirk of the Actor class. In short: Always keep a reference to your Actors, until you no longer want them.

Hi, welcome to the community!

The answers above are correct. “But,” you might reasonably wonder, “why does the model still show but the animation doesn’t? Shouldn’t the model also be garbage collected?”

The answer is that the model is placed in the scene graph via reparentTo, so a reference is kept around. But Actor is a Python wrapper around the underlying model, and this Python wrapper doesn’t live in the scene graph. So, the Python wrapper gets cleaned up while the C++ model lives on. (You can set the Actor wrapper as a Python tag onto the underlying scene graph node, but I wouldn’t recommend it as this opens a can of worms)

1 Like

Ok, I understood, I will consider the references to keep it alive and read a little about recycling.
Thank you.