+1 vote

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?

asked Jun 27 in Engine by jahu00 (45 points)

1 Answer

+1 vote

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.

answered Jun 27 by jahu00 (45 points)

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.

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.