C#: Cannot access a disposed object

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Christoffer Schindel

Hi,

So I’m having some trouble trying to figure out why I’m getting the error

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'Godot.RigidBody'.

  <C Source>     :0
  <Stack Trace>  :0 @ ()
  Object.cs:338 @ System.Object Godot.Object.Call(System.String , System.Object[] )()
  cameraController.cs:52 @ void cameraController._Input(Godot.InputEvent )()

I’ve come to the conclusion that it’s because it can’t find my RigidBody node…
However, I am declaring that node like this:

public class test : Node {
    RigidBody player;
        public override void _Ready() {
            player = GetNode("/root/Scene/player") as RigidBody;

So when _Ready has been initialized, I should be able to fetch it from anywhere in my script, right? At least, I can do that with all my other scripts, but not with this one for some reason.

If I declare the RigidBody node right before I need to use it in my if statement, it works fine, e.g.:

public void blabla() {
    if ( true ) {
        RigidBody player = GetNode("/root/Scene/player");
        // do stuff with player node
    }

Anyone know what’s up? I can’t for the life of me figure out why it wont access that node. I’m not disposing of it anywhere, or using QueueFree().
Using 3.1 stable Mono.

As a note, you can check if a reference is valid using IsInstanceValid(node).

jjmontes | 2020-12-18 01:21

This problem could happen when you change the scene tree. In this case, the Player reference you loaded in the _Ready is disposed because there is another Player instance (located in the same node path) loaded in a second scene. So, is this error happening when you change the scene?

betauer | 2021-02-11 11:51

Hello. I have the same error happening when I am changing the scene. Do you know how to solve this error? Thanks in advance !

Dayls | 2021-07-06 19:04