Accessing a variable from an instance shouldn't be this hard?

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

Hi there, I’m fairly new to Godot Mono but have been coding in Unity for a while now. I finished the tutorial on the docs for your first game, but have been stuck ever since afterwards.

I’m trying to access a variable from an instanced ‘PackedScene’ object, but the editor will simply not budge.

The main scene:

public class Main : Node
	public PackedScene Scene;
	public override void _Ready()
		Node image = Scene.Instance();


The image scene:

public class Scene: Area2D
    public Sprite GetSprite => GetNode<Sprite>("Sprite");

	public int Width
		get => GetSprite.Texture.GetWidth();
	public int Height
		get => GetSprite.Texture.GetHeight();

The code is simplified for this question, but gives me this error;

Main.cs(23,18): error CS1061: 'Node' does not contain a definition for 'Width' and no accessible extension method 'Width' accepting a first argument of type 'Node' could be found (are you missing a using directive or an assembly reference?)

If I manually Instance the scene via the UI and use the following code, it does get the correct value; but that’s not what I’m after since I want to use dynamic instancing.


Thanks in advance.

When you define image in your main scene, you’re telling the interpreter that it is a Node class. Node doesn’t have a width parameter. Does it work if you switch the type in that declaration to Area2D? EDIT: I’m not sure if I understand, but you might be able to use Scene, not Area2D. Personally I think that class name is a little ambiguous.

DDoop | 2020-07-19 16:49

I’ve tried casting it to Area2D as well, same error but now with Area2D. Scene isn’t the actual name, maybe I should’ve specified that!

Kajirinn | 2020-07-19 17:01

Frankly, I’m confused as well, I never got very far with Mono. The properties Width and Height exist in the public class Scene block, so I’d expect you’d need to cast to (or declare it as) the class Scene. If that’s not the name, why is it called that in your code?

DDoop | 2020-07-19 17:09

:bust_in_silhouette: Reply From: JimArtificer

Glad to see more C# questions on here.

The problem:
Node image = Scene.Instance();

You are treating image as a Node in this method, not as a Scene. The Instance() method returns a Node.

There are a few ways to cast an object in C# depending on how you intend to handle null objects. One example:
Scene myVar = Scene.Instance() as Scene;

Thank you so much, that makes so much sense; can’t believe I didn’t try that. Cheers!

Kajirinn | 2020-07-19 21:57