How to instance C# class

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

I have a C# script attached to a scene:

using Godot;
using System;

public class MyScene : Node
{
    public override void _Ready()
    {
        var myClass = new MyClass("abc");
    }
}

And a class in another file:

using System;
using Godot;

public class MyClass
{
    protected string Prop { get; set; }

    public MyClass(string propName)
    {
        Prop = propName;
    }
}

When I try to run/build the game, Godot informs me that the it cannot find the class in question. Can I actually instance this class or it can’t be done? If it can be done, how can I do this?

:bust_in_silhouette: Reply From: jahu00

After wasting an hour trying to figure out what I’m doing wrong, it turns out, the above code is correct. The problem was MyClass not begin compiled. I’ve added the file using VSCode, but for it to get compiled it needs to be in the .csproj file.

After adding it manually to the project file everything compiles and runs ok.

Before in .csproj file there was:

  <ItemGroup>
    <Compile Include="MyScene.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>

And now there is:

  <ItemGroup>
    <Compile Include="MyScene.cs" />
	<Compile Include="MyClass.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>

Is this normal that adding files from VSCode doesn’t add them to .csproj file?

Probably if I added the script from inside Godot, it would complie fine from the start.

This site helped me out https://medium.com/@domresc/ep-2-basics-of-developing-a-video-game-with-godot-engine-in-c-121f46429c00. The author mentioned cs files not being removed from .csproj file. My problem was the exact opposite.

jahu00 | 2020-06-27 19:13

Likely what happened was that when you added something to the .csproj file outside of Godot’s editor it wasn’t saved. (Visual Studio 2019 doesn’t save project file settings on compile, for example. You have to do File > Save All.)

Then you returned to Godot and it re-saved the project file as part of running a scene. If you returned to your external editor and it picked up the saved file’s timestamp then the changes you had in memory are lost when it is reloaded.

JimArtificer | 2020-06-27 19:29