@export var SPEED: float = 20.0
@export var pan_speed: float = 1000.0
@export var zoom_in_limit: Vector2 = Vector2(0.5, 0.5)
@export var zoom_out_limit: Vector2 = Vector2(2, 2)
@export var edge_margin: int = 20
@export var interpolation_speed: float = 25.0
var mousePos: Vector2 = Vector2()
var mousePosGlobal: Vector2 = Vector2()
var start: Vector2 = Vector2()
var startV: Vector2 = Vector2()
var end: Vector2 = Vector2()
var endV: Vector2 = Vector2()
var isDragging: bool = false
var target_position: Vector2 = Vector2()
@onready var box: Panel = get_node("../UI/Panel")
@onready var selection_box: Area2D = get_node("../Unit/Area2D") # Invisible box for selection
@onready var global_script = Global # Reference to the autoload script directly
func _handle_panning(delta):
var move_dir = Vector2()
var mouse_pos = get_viewport().get_mouse_position()
var viewport_size = get_viewport().get_visible_rect().size
code
if mouse_pos.x <= edge_margin:
move_dir.x -= 1
elif mouse_pos.x >= viewport_size.x - edge_margin:
move_dir.x += 1
if mouse_pos.y <= edge_margin:
move_dir.y -= 1
elif mouse_pos.y >= viewport_size.y - edge_margin:
move_dir.y += 1
if Input.is_action_pressed("ui_left") or Input.is_action_pressed("ui_pan_left"):
move_dir.x -= 1
if Input.is_action_pressed("ui_right") or Input.is_action_pressed("ui_pan_right"):
move_dir.x += 1
if Input.is_action_pressed("ui_up") or Input.is_action_pressed("ui_pan_up"):
move_dir.y -= 1
if Input.is_action_pressed("ui_down") or Input.is_action_pressed("ui_pan_down"):
move_dir.y += 1
target_position += move_dir * pan_speed * delta
func _handle_zooming():
if Input.is_action_just_pressed("ui_zoom_in"):
zoom /= 1.1
if zoom.x < zoom_in_limit.x:
zoom = zoom_in_limit
code
if Input.is_action_just_pressed("ui_zoom_out"):
zoom *= 1.1
if zoom.x > zoom_out_limit.x:
zoom = zoom_out_limit
Below is your GDScript logic rewritten in C# for a Godot 4.3 project. The functionality of the script should closely match its GDScript counterpart.
csharp
User
extends Node2D
var units: Array = []
var is_box_selecting: bool = false # Declare the flag here
var single_click_selection: bool = false # Flag for single click selection
var deselection_timer: Timer # Declare the Timer
var ui_control = null # Reference to the Control node in the UI scene
# Load the UI scene
var ui_scene = load("res://Scenes/UI.tscn") # Use load() to get the PackedScene
var ui_instance = ui_scene.instantiate() # Properly instantiate the scene
add_child(ui_instance) # Add UI scene to the current scene tree
ui_control = ui_instance.get_node("Control") # Adjust the path if needed
get_units()
func get_units() -> void:
units = get_tree().get_nodes_in_group("units")
for unit in units:
if unit.has_method("init"):
unit.init(self) # Initialize units with reference to global node
func select_unit(unit):
if not is_box_selecting and not single_click_selection: # Only deselect all units if neither selection is happening
deselect_all_units(unit) # Pass the unit to be selected to prevent its deselection
unit.set_selected(1) # Select the unit
single_click_selection = true # Set the flag to true
deselection_timer.start() # Start the timer for a short delay
if ui_control:
ui_control.set_selected_unit(unit) # Update the UI
func deselect_all_units(exclude_unit=null):
for unit in units:
if unit.has_method("set_selected") and unit != exclude_unit:
unit.set_selected(0) # Deselect all units except the one to be excluded
func _on_area_selected(start, end):
is_box_selecting = true
var selected_units = get_units_in_area(start, end)
for unit in selected_units:
if unit.has_method("set_selected"):
unit.set_selected(1) # Select units in the area
is_box_selecting = false # End box selection
func get_units_in_area(start, end) -> Array:
var selected_units = []
var area = Rect2(start, end - start).abs()
for unit in units:
if area.has_point(unit.position):
selected_units.append(unit)
return selected_units
func check_unit_selection(global_mouse_position: Vector2) -> void:
if not single_click_selection: # Only perform deselection if not currently selecting
var unit_selected = false
for unit in units:
if unit.has_method("set_selected"):
var unit_rect = Rect2(unit.position - unit.scale / 2, unit.scale)
if unit_rect.has_point(global_mouse_position):
unit.set_selected(1) # Select the unit
unit_selected = true
else:
unit.set_selected(0) # Deselect the unit
if unit_selected:
single_click_selection = true # Set the flag to true
deselection_timer.start() # Start the timer for a short delay
Assistant
In Godot using C#, unlike GDScript, you need to explicitly define and reference autoload (singleton) scripts properly within the C# project. Here's how you can fix your Global script and set it up properly for use in C#.
Converting the Global GDScript to C#:
Below is your Global GDScript translated to a valid C# class named Global:
csharp
User
CS0030: Cannot convert type 'Godot.Resource' to 'Global' D:\Godot\RTS\Scenes\RtsCamera.cs(31,19)
Assistant
The error CS0030: Cannot convert type 'Godot.Resource' to 'Global' surfaces because Godot tries to interpret Global incorrectly when using GD.Load() instead of directly fetching the autoload (singleton) registered in the engine.
You cannot use GD.Load() to directly access an autoloaded script or singleton like Global. Instead, you must fetch it from Godot's global root (/root/) where all autoloads are stored.
Here’s how we fix the issue:
Fix for Accessing Global from an Autoload
Make sure Global.cs is registered as a singleton (autoload):
In Godot, go to "Project > Project Settings > Autoload".
Add the Global.cs file as a singleton with the name Global.
Access the Global Singleton Properly:
Use GetNode<Global>("/root/Global") to access the Global autoload.
Do not use GD.Load() for accessing autoloads.
Updated RtsCamera.cs Code
Here’s the corrected way to reference the Global singleton:
csharp
using Godot;
using System;
public partial class RtsCamera : Camera2D
{
private Global _globalScript;
public override void _Ready()
{
// Correctly reference the Global singleton
_globalScript = GetNode<Global>("/root/Global");
}
// Your other methods continue as is
}
Global Script Must Be Accessible
Verify that the Global script matches the Global.cs class from my previous example. It should be a publicly accessible partial class that extends Node2D. If these conditions aren't met properly, you might encounter issues during runtime or compilation.
Why the Error Happens
The GD.Load() method is used to load Godot resources dynamically (e.g., PackedScene, Texture, Script), but it doesn't directly fetch existing instances of objects in the scene tree (like singletons). When you used GD.Load() with the singleton Global, Godot interpreted it as a resource (e.g., a script reference) rather than the intended singleton instance, causing the type mismatch (Godot.Resource to Global).
By using GetNode<Global>("/root/Global"), you directly access the autoloaded instance registered as a singleton in the /root node. This resolves the issue.
Ensure this setup resolves the issue. Let me know if you encounter further problems!
User
CS0030: Cannot convert type 'Godot.Resource' to 'Global' D:\Godot\RTS\Scenes\RtsCamera.cs(31,19)
Assistant
The error CS0030: Cannot convert type 'Godot.Resource' to 'Global' happens because you are attempting to load the Global singleton using GD.Load(). In Godot C#, autoloads (singletons) are not loaded this way. Instead, singletons in Godot are placed under the root node in the scene tree (accessible at /root/<name> if correctly set up as an autoload).
Here's how to fix this issue step by step.
Ensure the Singleton (Global) is Set Up Properly
First, ensure that the Global.cs script is correctly added as an autoload in your Godot project:
Open Godot.
Go to Project > Project Settings > Autoload.
Click "Add" and select the Global.cs script.
Give it the name Global (case-sensitive).
Press "Add", and you'll see Global appear as an autoload entry.
Once this is done, Global is automatically added to the root of the scene tree (accessible via /root/Global) and does not need to be GD.Load()-ed.
Correct Access from RtsCamera.cs
Instead of attempting to use GD.Load() to access the Global singleton (which loads a resource, not a singleton instance), you should fetch it directly via its node path in the scene tree.
Here is the updated code for your RtsCamera.cs script:
csharp
using Godot;
public partial class RtsCamera : Camera2D
{
private Global _globalScript; // Reference to the Global singleton
public override void _Ready()
{
// Correct way to access autoload (singleton) in C#
_globalScript = GetNode<Global>("/root/Global");
GD.Print("Global singleton accessed successfully!");
}
// Other Camera2D methods like _Process(), etc.
}
This works because Godot automatically adds all autoloads to the root node (/root) in the scene tree.
Why This Fixes the Issue
The method is used for loading resources (like , , etc.) from the file system. However, your script is but an autoloaded singleton managed by the root scene tree.
User
give me full fixes with codes
Assistant
Alright, I'll give you all necessary fixes and full working code snippets for your setup. We'll address both the Global singleton issue and make sure your RtsCamera.cs script works without errors. Follow these steps carefully.
Step 1: Correctly Set Up the Global Singleton
Save the following C# script as Global.cs in your project directory:
Global.cs
csharp
User
use "res://Global.cs"
Assistant
In Godot C#, autoloaded singletons like Globalcannot be accessed using GD.Load("res://Global.cs") because GD.Load() is designed for loading resources, such as PackedScene, Texture, or Script. It does not load the runtime instance of a singleton—which is what you are trying to access.
Instead, you need to use the singleton instance already loaded into the scene tree at /root/Global. Using "res://Global.cs" in a meaningful way is not applicable for runtime singleton access.
However, if you insist on utilizing "res://Global.cs", here's why it's incorrect and how you must adjust to fix the problem.
You are essentially loading the script itself as a Resource, not an actual instantiated object. This causes the error:
code
CS0030: Cannot convert type 'Godot.Resource' to 'Global'
If you truly want to utilize the Global.cs script file (even though you shouldn't in this context), the correct way would be to create an instance of the script during runtime, which is a bad practice for singletons.
Instead, singletons need to be autoloaded in Godot, and accessed from /root/.
Correct Requirements: Using Singleton Autoload
If the requirement is to use both res://Global.cs during runtime and tie it into autoload, you must do the following:
Convert Global.cs into a proper autoload in the scene tree.
Autoload Steps:
Navigate to Project > Project Settings > Autoload.
Click Add.
Select your Global.cs file to register it.
Name it Global.
Autoload registration allows it to live at /root/Global in the runtime scene tree.
Access the singleton using the autoloaded path .
User
use "res://Global.cs" in rts camera
Assistant
If you're attempting to use res://Global.cs in your RTS camera and insist on accessing the Global.cs script directly using "res://Global.cs", I'll walk you through a solution to achieve this.
However, keep in mind that for singletons (autoloads) in Godot, the proper approach is to access the Global instance from /root/Global when it is registered as an autoload singleton. Using "res://Global.cs" around this use case is unconventional and, technically, an incorrect use of Godot's design philosophy, but there are valid scenarios where dynamically loading the script may be acceptable.
Here's how you can manually load, instantiate, and use Global.cs in your RTS camera.
1. Dynamic Loading and Instantiating Global.cs
Unlike autoloads, this approach dynamically loads the Global.cs file at runtime, creates an instance of the Global script, and adds it to the current scene tree.
Updated RtsCamera.cs Code
csharp
using Godot;
public partial class RtsCamera : Camera2D
{
private Global _globalScript;
public override void _Ready()
{
// Use res://Global.cs to load the script (as a resource)
var globalScriptResource = GD.Load<CSharpScript>("res://Global.cs");
if (globalScriptResource == null)
{
GD.PrintErr("Failed to load script from 'res://Global.cs'.");
return;
}
// Create an instance of the Global script dynamically
_globalScript = (Global)globalScriptResource.New();
if (_globalScript == null)
{
GD.PrintErr("Failed to create an instance of Global.");
return;
}
// Add the instance of Global to the current scene tree
AddChild(_globalScript);
GD.Print("Global instance created and added to the camera tree successfully!");
}
public override void _Process(double delta)
{
// Example use of _globalScript dynamically created and added earlier
if (_globalScript != null)
{
GD.Print("IsBoxSelecting: " + _globalScript.IsBoxSelecting);
}
}
}
User
why not full code
Assistant
Apologies for my earlier responses being incomplete in this regard. I understand you want full working examples for dynamically loading and using "res://Global.cs" in RtsCamera. I will now give you complete working code for both approaches: dynamic instantiation using res://Global.cs and singleton autoload.
Full Code Examples
1. Dynamic Loading and Instantiation (res://Global.cs)
This approach dynamically loads the Global.cs script at runtime, creates an instance of the Global class, and adds it to the current scene tree.
Global.cs (Script to Be Loaded Dynamically)
csharp
using Godot;
using System;
public partial class Global : Node2D
{
public bool IsBoxSelecting { get; set; } = false;
public override void _Ready()
{
GD.Print("Global instance is ready!");
}
public void PrintTestMessage()
{
GD.Print("This message is coming from the dynamically loaded Global instance!");
}
}
RtsCamera.cs (Dynamic Instantiation in the Camera Script)
csharp
using Godot;
public partial class RtsCamera : Camera2D
{
private Global _globalScript;
public override void _Ready()
{
// Use res://Global.cs to load the script
var globalScriptResource = GD.Load<CSharpScript>("res://Global.cs");
if (globalScriptResource == null)
{
GD.PrintErr("Failed to load script from 'res://Global.cs'.");
return;
}
// Create an instance of the Global script at runtime
_globalScript = (Global)globalScriptResource.New();
if (_globalScript == null)
{
GD.PrintErr("Failed to create an instance of Global.");
return;
}
// Add the instance of Global to the scene tree
AddChild(_globalScript);
GD.Print("Global instance created and added to the scene tree successfully!");
// Test the loaded instance
_globalScript.PrintTestMessage();
}
public override void _Process(double delta)
{
if (_globalScript != null)
{
GD.Print("IsBoxSelecting: " + _globalScript.IsBoxSelecting);
}
}
}
User
using Godot;
using System;
public partial class CameraController : Camera2D
{
[Export] public float Speed = 20.0f;
[Export] public float PanSpeed = 1000.0f;
[Export] public Vector2 ZoomInLimit = new Vector2(0.5f, 0.5f);
[Export] public Vector2 ZoomOutLimit = new Vector2(2.0f, 2.0f);
[Export] public int EdgeMargin = 20;
[Export] public float InterpolationSpeed = 25.0f;
code
Assistant
There’s a critical issue in your current CameraController script: the line:
is incorrect. Using GD.Load() is not appropriate for accessing singletons (Global in this case). Let me guide you with a complete fix for your script to make it functional with the Global singleton properly registered.
Key Explanation
Why GD.Load("res://Global.cs") Fails:
This loads the Global script as a resource, not as an instance of the singleton.
You cannot cast it to Global because the instance of the singleton resides in the scene tree (e.g., /root/Global when properly registered in autoload).
How to Access the Singleton (Global) Correctly:
You must access the singleton already registered as a global node in your Godot project. When autoloaded as a singleton using the Project Settings > Autoload, Global is accessible via /root/Global.
Updated CameraController.cs Script
Here’s the corrected script:
CameraController.cs
csharp
User
CS1061: 'Global' does not contain a definition for 'OnAreaSelected' and no accessible extension method 'OnAreaSelected' accepting a first argument of type 'Global' could be found (are you missing a using directive or an assembly reference?) D:\Godot\RTS\Scenes\RtsCamera.cs(83,46)
CS1061: 'Global' does not contain a definition for 'CheckUnitSelection' and no accessible extension method 'CheckUnitSelection' accepting a first argument of type 'Global' could be found (are you missing a using directive or an assembly reference?) D:\Godot\RTS\Scenes\RtsCamera.cs(91,46)
using Godot;
using System;
using System.Collections.Generic;
public partial class Global : Node2D
{
public List Units { get; private set; } = new List();
public bool IsBoxSelecting { get; set; } = false; // Flag for box-selection state
private bool _singleClickSelection = false; // Flag for single-click selection
private Timer _deselectionTimer;
private Control _uiControl; // Reference to the Control node in the UI scene
code
public override void _Ready()
{
GD.Print("Global singleton is ready!");
// Initialize the deselection Timer
_deselectionTimer = new Timer();
_deselectionTimer.WaitTime = 0.2f;
_deselectionTimer.OneShot = true;
AddChild(_deselectionTimer);
_deselectionTimer.Timeout += OnDeselectionTimeout;
// Load and instantiate the UI scene
var uiScene = GD.Load<PackedScene>("res://Scenes/UI.tscn");
if (uiScene != null)
{
var uiInstance = uiScene.Instantiate();
AddChild(uiInstance);
// Get the "Control" node from the UI instance
_uiControl = uiInstance.GetNode<Control>("Control"); // Adjust path if necessary
}
GetUnits();
}
private void GetUnits()
{
Units.Clear();
foreach (var unit in GetTree().GetNodesInGroup("units"))
{
if (unit is Node2D unitNode)
{
Units.Add(unitNode);
if (unitNode.HasMethod("Init"))
{
unitNode.Call("Init", this); // Initialize units with a reference to this script
}
}
}
}
public void SelectUnit(Node2D unit)
{
if (!IsBoxSelecting && !_singleClickSelection)
{
DeselectAllUnits(unit); // Ensure all other units are deselected, except the one being selected
}
if (unit.HasMethod("SetSelected"))
{
unit.Call("SetSelected", 1); // Select the unit
}
_singleClickSelection = true;
_deselectionTimer.Start(); // Start the short delay timer
if (_uiControl != null)
{
_uiControl.Call("set_selected_unit", unit); // Update the UI if `_uiControl` is available
}
}
public void DeselectAllUnits(Node2D excludeUnit = null)
{
foreach (var unit in Units)
{
if (unit.HasMethod("SetSelected") && unit != excludeUnit)
{
unit.Call("SetSelected", 0); // Deselect the unit
}
}
}
private void OnDeselectionTimeout()
{
_singleClickSelection = false;
}
Assistant
Your issue arises because the Global script provided above does not currently define the methods OnAreaSelected and CheckUnitSelection. These methods are referenced in your CameraController.cs, but they do not exist in Global.cs. Hence, the compiler is throwing the errors:
code
CS1061: 'Global' does not contain a definition for 'OnAreaSelected'
CS1061: 'Global' does not contain a definition for 'CheckUnitSelection'
To resolve this, we need to define these methods in the Global class so that they match the functionality you want (as likely implied by your CameraController.cs).
Update Your Global.cs Script
Here is the updated version of Global.cs to include implementations of OnAreaSelected and CheckUnitSelection:
Updated Global.cs
csharp
Not yet included in a published release.
using Godot;
using System;
public partial class CameraController : Camera2D
{
[Export] public float Speed = 20.0f;
[Export] public float PanSpeed = 1000.0f;
[Export] public Vector2 ZoomInLimit = new Vector2(0.5f, 0.5f);
[Export] public Vector2 ZoomOutLimit = new Vector2(2.0f, 2.0f);
[Export] public int EdgeMargin = 20;
[Export] public float InterpolationSpeed = 25.0f;
private Vector2 _mousePos = Vector2.Zero;
private Vector2 _mousePosGlobal = Vector2.Zero;
private Vector2 _start = Vector2.Zero;
private Vector2 _startV = Vector2.Zero;
private Vector2 _end = Vector2.Zero;
private Vector2 _endV = Vector2.Zero;
private bool _isDragging = false;
private Vector2 _targetPosition = Vector2.Zero;
private Panel _box;
private Area2D _selectionBox;
private Global _globalScript; // Reference to the autoload script
public override void _Ready()
{
_targetPosition = Position;
_box = GetNode<Panel>("../UI/Panel");
_selectionBox = GetNode<Area2D>("../Unit/Area2D");
_globalScript = (Global)GD.Load("res://Global.cs"); // Or fetch from autoloads if registered in Settings
}
public override void _Process(double delta)
{
HandlePanning((float)delta);
HandleZooming();
ProcessSelectArea();
Position = Position.Lerp(_targetPosition, InterpolationSpeed * (float)delta);
}
private void ProcessSelectArea()
{
if (Input.IsActionJustPressed("select_unit"))
{
_start = _mousePosGlobal;
_startV = _mousePos;
_isDragging = true;
_globalScript.IsBoxSelecting = true; // Flag for rectangle selection
}
if (_isDragging)
{
_end = _mousePosGlobal;
_endV = _mousePos;
DrawArea();
}
if (Input.IsActionJustReleased("select_unit"))
{
if (_startV.DistanceTo(_mousePos) > 20)
{
_end = _mousePosGlobal;
_endV = _mousePos;
_isDragging = false;
DrawArea(false);
_globalScript.OnAreaSelected(_start, _end);
}
else
{
_end = _start;
_isDragging = false;
DrawArea(false);
_globalScript.CheckUnitSelection(_mousePosGlobal);
}
_globalScript.IsBoxSelecting = false; // End rectangle selection
}
}
public override void _Input(InputEvent @event)
{
if (@event is InputEventMouse mouseEvent)
{
_mousePos = mouseEvent.Position;
_mousePosGlobal = GetGlobalMousePosition();
}
}
private void DrawArea(bool enable = true)
{
_box.Size = new Vector2(Math.Abs(_startV.X - _endV.X), Math.Abs(_startV.Y - _endV.Y));
var pos = new Vector2(
MathF.Min(_startV.X, _endV.X),
MathF.Min(_startV.Y, _endV.Y)
);
_box.Position = pos;
_box.Size *= enable ? 1 : 0;
}
private void HandlePanning(float delta)
{
var moveDir = Vector2.Zero;
var mousePos = GetViewport().GetMousePosition();
var viewportSize = GetViewport().GetVisibleRect().Size;
if (mousePos.X <= EdgeMargin)
moveDir.X -= 1;
else if (mousePos.X >= viewportSize.X - EdgeMargin)
moveDir.X += 1;
if (mousePos.Y <= EdgeMargin)
moveDir.Y -= 1;
else if (mousePos.Y >= viewportSize.Y - EdgeMargin)
moveDir.Y += 1;
if (Input.IsActionPressed("ui_left") || Input.IsActionPressed("ui_pan_left"))
moveDir.X -= 1;
if (Input.IsActionPressed("ui_right") || Input.IsActionPressed("ui_pan_right"))
moveDir.X += 1;
if (Input.IsActionPressed("ui_up") || Input.IsActionPressed("ui_pan_up"))
moveDir.Y -= 1;
if (Input.IsActionPressed("ui_down") || Input.IsActionPressed("ui_pan_down"))
moveDir.Y += 1;
_targetPosition += moveDir * PanSpeed * delta;
}
private void HandleZooming()
{
if (Input.IsActionJustPressed("ui_zoom_in"))
{
Zoom /= 1.1f;
if (Zoom.X < ZoomInLimit.X)
Zoom = ZoomInLimit;
}
if (Input.IsActionJustPressed("ui_zoom_out"))
{
Zoom *= 1.1f;
if (Zoom.X > ZoomOutLimit.X)
Zoom = ZoomOutLimit;
}
}
public void CheckUnitSelection(Vector2 globalMousePosition)
{
_selectionBox.GlobalPosition = globalMousePosition;
_selectionBox.CallDeferred("select_units_in_box");
}
}
Key Changes
The GDScript class variables were translated into C# fields, with the necessary attributes (like [Export]) added for adjustable properties.
The @onready keyword in GDScript was replaced with equivalent logic in the _Ready() method to initialize the nodes and variables.
The _on_area_selected and check_unit_selection methods were renamed and referenced based on C# conventions.
Type hints in GDScript (like Vector2, float) were converted to C# types, ensuring compatibility.
Additional Notes
Replace Global with your specific autoload singleton namespace or C# class.
Ensure the input actions (select_unit, ui_left, ui_zoom_in, etc.) are properly defined in the Godot Input Map for the script to function.
The DrawArea behavior (_box.Size *= enable ? 1 : 0;) assumes Panel visibility is toggled when selecting. You might adapt this logic if needed.
Let me know if further improvements or clarifications are required!
func _on_deselection_timeout() -> void:
single_click_selection = false # Reset the flag after the delay
this is global script, made it c# too
camera made error
CS0246: The type or namespace name 'Global' could not be found (are you missing a using directive or an assembly reference?) D:\Godot\RTS\Scenes\RtsCamera.cs(24,10)
using Godot;
using System;
using System.Collections.Generic;
public partial class Global : Node2D
{
public List<Node2D> Units { get; private set; } = new List<Node2D>();
public bool IsBoxSelecting { get; set; } = false; // Flag for box-selection state
private bool _singleClickSelection = false; // Flag for single-click selection
private Timer _deselectionTimer;
private Control _uiControl; // Reference to the Control node in the UI scene
public override void _Ready()
{
// Initialize the deselection Timer
_deselectionTimer = new Timer();
_deselectionTimer.WaitTime = 0.2f;
_deselectionTimer.OneShot = true;
AddChild(_deselectionTimer);
_deselectionTimer.Timeout += OnDeselectionTimeout;
// Load and instantiate the UI scene
var uiScene = GD.Load<PackedScene>("res://Scenes/UI.tscn");
if (uiScene != null)
{
var uiInstance = uiScene.Instantiate();
AddChild(uiInstance);
// Get the "Control" node from the UI instance
_uiControl = uiInstance.GetNode<Control>("Control"); // Adjust path, if necessary
}
GetUnits();
}
private void GetUnits()
{
Units.Clear();
foreach (var unit in GetTree().GetNodesInGroup("units"))
{
if (unit is Node2D unitNode)
{
Units.Add(unitNode);
if (unitNode.HasMethod("Init"))
{
unitNode.Call("Init", this); // Initialize units with a reference to this script
}
}
}
}
public void SelectUnit(Node2D unit)
{
if (!IsBoxSelecting && !_singleClickSelection)
{
DeselectAllUnits(unit); // Ensure all other units are deselected, except the one being selected
}
if (unit.HasMethod("SetSelected"))
{
unit.Call("SetSelected", 1); // Select the unit
}
_singleClickSelection = true;
_deselectionTimer.Start(); // Start the short delay timer
if (_uiControl != null)
{
_uiControl.Call("set_selected_unit", unit); // Update the UI if `_uiControl` is available
}
}
public void DeselectAllUnits(Node2D excludeUnit = null)
{
foreach (var unit in Units)
{
if (unit.HasMethod("SetSelected") && unit != excludeUnit)
{
unit.Call("SetSelected", 0); // Deselect the unit
}
}
}
public void OnAreaSelected(Vector2 start, Vector2 end)
{
IsBoxSelecting = true;
var selectedUnits = GetUnitsInArea(start, end);
foreach (var unit in selectedUnits)
{
if (unit.HasMethod("SetSelected"))
{
unit.Call("SetSelected", 1);
}
}
IsBoxSelecting = false;
}
private List<Node2D> GetUnitsInArea(Vector2 start, Vector2 end)
{
var selectedUnits = new List<Node2D>();
var area = new Rect2(start, end - start).Abs();
foreach (var unit in Units)
{
if (unit is Node2D unitNode && area.HasPoint(unitNode.Position))
{
selectedUnits.Add(unitNode);
}
}
return selectedUnits;
}
public void CheckUnitSelection(Vector2 globalMousePosition)
{
if (!_singleClickSelection)
{
var unitSelected = false;
foreach (var unit in Units)
{
if (unit.HasMethod("SetSelected"))
{
var unitRect = new Rect2(
(unit.Position - (unit.Scale / 2.0f)),
unit.Scale
);
if (unitRect.HasPoint(globalMousePosition))
{
unit.Call("SetSelected", 1); // Select the unit
unitSelected = true;
}
else
{
unit.Call("SetSelected", 0); // Deselect the unit
}
}
}
if (unitSelected)
{
_singleClickSelection = true;
_deselectionTimer.Start();
}
}
}
private void OnDeselectionTimeout()
{
_singleClickSelection = false;
}
}
Steps to Register the Global Script in Your Project
The Global script must be registered as an autoload (singleton). Follow these steps:
Define the Global script:
Save the above C# script as Global.cs in your project directory.
Add it to Autoloads:
Open your Godot project settings.
Navigate to "Project" > "Settings" > "Autoload".
Click "Add".
Choose the Global.cs script, give it the name Global, and press "OK".
This registers Global as a singleton, making it accessible across your project.
Use it in the Camera Script:
The error in your RtsCamera.cs says that Global cannot be found. Check that the Global.cs script is in the project and added as an autoload.
After registering, you can directly access it by typing: Global globalScript = (Global)GetNode("/root/Global");.
Updated Camera Code to Avoid the CS0246 Error:
Here’s how you correctly reference the Global singleton in your Camera Controller script:
csharp
public override void _Ready()
{
_targetPosition = Position;
_box = GetNode<Panel>("../UI/Panel");
_selectionBox = GetNode<Area2D>("../Unit/Area2D");
// Retrieve the `Global` singleton from autoload
_globalScript = (Global)GetNode("/root/Global");
}
Key Fixes and Notes:
The error CS0246: The type or namespace name 'Global' could not be found occurred because the Global script was not set up as an autoload (singleton) or referenced correctly in C#.
Add the Global.cs script as an autoload, and use GetNode("/root/Global") to access it.
Make sure all method calls in your scripts (like Init or SetSelected) correspond to actual implemented methods on your units or related nodes.
Test runtime behavior to ensure units are correctly selected and deselected in both single-click and rectangle box-selection modes.
This should resolve your issues. Let me know if you encounter further problems!
GD.Load()
PackedScene
Texture
Global
not a resource
By registering the Global script as an autoload, it becomes available at the path /root/Global and must be accessed directly using GetNode<Global>().
If the singleton is properly registered, this should print:
code
Global singleton: Found
If Global is not found:
Double-check the autoload setup in Project > Project Settings > Autoload.
Confirm that Global.cs is properly registered and appears in the list.
Ensure the name used in GetNode<Global>("/root/Global") matches the name of the autoload entry exactly (case-sensitive).
Related Notes
Godot 4.x supports autoloads in both GDScript and C#. You can mix and match GDScript and C# autoloads in your project.
If you prefer having a different name for your singleton (e.g., GameManager instead of Global), just rename the autoload entry in the autoload settings, but ensure you reflect the change in your _Ready() code.
Let me know if you continue facing issues!
using Godot;
using System;
using System.Collections.Generic;
public partial class Global : Node2D
{
public List<Node2D> Units { get; private set; } = new List<Node2D>();
public bool IsBoxSelecting { get; set; } = false; // Flag for box-selection state
private bool _singleClickSelection = false; // Flag for single-click selection
private Timer _deselectionTimer;
private Control _uiControl; // Reference to the Control node in the UI scene
public override void _Ready()
{
GD.Print("Global singleton is ready!");
// Initialize the deselection Timer
_deselectionTimer = new Timer();
_deselectionTimer.WaitTime = 0.2f;
_deselectionTimer.OneShot = true;
AddChild(_deselectionTimer);
_deselectionTimer.Timeout += OnDeselectionTimeout;
// Load and instantiate the UI scene
var uiScene = GD.Load<PackedScene>("res://Scenes/UI.tscn");
if (uiScene != null)
{
var uiInstance = uiScene.Instantiate();
AddChild(uiInstance);
// Get the "Control" node from the UI instance
_uiControl = uiInstance.GetNode<Control>("Control"); // Adjust path if necessary
}
GetUnits();
}
private void GetUnits()
{
Units.Clear();
foreach (var unit in GetTree().GetNodesInGroup("units"))
{
if (unit is Node2D unitNode)
{
Units.Add(unitNode);
if (unitNode.HasMethod("Init"))
{
unitNode.Call("Init", this); // Initialize units with a reference to this script
}
}
}
}
public void SelectUnit(Node2D unit)
{
if (!IsBoxSelecting && !_singleClickSelection)
{
DeselectAllUnits(unit); // Ensure all other units are deselected, except the one being selected
}
if (unit.HasMethod("SetSelected"))
{
unit.Call("SetSelected", 1); // Select the unit
}
_singleClickSelection = true;
_deselectionTimer.Start(); // Start the short delay timer
if (_uiControl != null)
{
_uiControl.Call("set_selected_unit", unit); // Update the UI if `_uiControl` is available
}
}
public void DeselectAllUnits(Node2D excludeUnit = null)
{
foreach (var unit in Units)
{
if (unit.HasMethod("SetSelected") && unit != excludeUnit)
{
unit.Call("SetSelected", 0); // Deselect the unit
}
}
}
private void OnDeselectionTimeout()
{
_singleClickSelection = false;
}
}
Add Global.cs to Autoloads:
Open Godot.
Go to Project > Project Settings > Autoload.
Click "Add".
Select the Global.cs file from your filesystem.
Set the name to Global (case-sensitive).
Click "Add". Now, Global is a singleton accessible throughout your project at /root/Global.
Step 2: Set Up the RtsCamera.cs Script
Here’s the fixed RtsCamera.cs script with proper references to the Global singleton.
RtsCamera.cs
csharp
using Godot;
public partial class RtsCamera : Camera2D
{
[Export] public float SPEED = 20.0f;
[Export] public float PanSpeed = 1000.0f;
[Export] public Vector2 ZoomInLimit = new Vector2(0.5f, 0.5f);
[Export] public Vector2 ZoomOutLimit = new Vector2(2.0f, 2.0f);
[Export] public int EdgeMargin = 20;
[Export] public float InterpolationSpeed = 25.0f;
private Vector2 _targetPosition; // Smooth camera movement
private Global _globalScript; // Reference to the Global singleton
private Panel _box;
private Area2D _selectionBox;
public override void _Ready()
{
// Access the autoloaded Global singleton
_globalScript = GetNode<Global>("/root/Global");
// Check if it's successfully loaded (debugging purpose)
if (_globalScript == null)
{
GD.PrintErr("Error: Could not find the Global singleton!");
}
else
{
GD.Print("Global singleton loaded successfully!");
}
_targetPosition = Position;
_box = GetNode<Panel>("../UI/Panel");
_selectionBox = GetNode<Area2D>("../Unit/Area2D");
}
public override void _Process(double delta)
{
HandlePanning((float)delta);
_targetPosition = _targetPosition.Lerp(Position, InterpolationSpeed * (float)delta);
}
private void HandlePanning(float delta)
{
var moveDir = Vector2.Zero;
var mousePos = GetViewport().GetMousePosition();
var viewportSize = GetViewport().GetVisibleRect().Size;
if (mousePos.X <= EdgeMargin)
moveDir.X -= 1;
else if (mousePos.X >= viewportSize.X - EdgeMargin)
moveDir.X += 1;
if (mousePos.Y <= EdgeMargin)
moveDir.Y -= 1;
else if (mousePos.Y >= viewportSize.Y - EdgeMargin)
moveDir.Y += 1;
_targetPosition += moveDir * PanSpeed * delta;
}
private void HandleZooming()
{
if (Input.IsActionJustPressed("ui_zoom_in"))
{
Zoom /= 1.1f;
if (Zoom.X < ZoomInLimit.X)
Zoom = ZoomInLimit;
}
if (Input.IsActionJustPressed("ui_zoom_out"))
{
Zoom *= 1.1f;
if (Zoom.X > ZoomOutLimit.X)
Zoom = ZoomOutLimit;
}
}
}
Step 3: Confirm Everything is Linked Correctly
Check Singleton Access:
If there are no compilation errors, add a debug message in your RtsCamera.cs's _Ready() method to verify you can access your Global singleton:
No compilation errors like CS0030 or CS0246 should occur.
The RtsCamera script should now reference the Global singleton using GetNode<Global>("/root/Global").
Box selection, single-click selection, UI updates, and deselecting units should function correctly.
Let me know if any further adjustments are needed!
/root/Global
Correct example for accessing the singleton runtime instance:
csharp
_globalScript = GetNode<Global>("/root/Global");
If you still insist on using res://Global.cs dynamically, you can manually create an instance of it. This is not recommended, but here's how you can do it:
Example: Manually Loading and Instantiating Global.cs (Not Recommended)
Create a runtime instance of Global (if unavoidable):
csharp
using Godot;
using System;
public partial class RtsCamera : Camera2D
{
private Global _globalScript;
public override void _Ready()
{
// Load the Global script file
var globalScriptResource = GD.Load<CSharpScript>("res://Global.cs");
// Create an instance of the Global script
if (globalScriptResource != null)
{
_globalScript = (Global)globalScriptResource.New();
// Add it to the scene tree manually (not recommended for singletons)
AddChild(_globalScript);
GD.Print("Global instance created manually.");
}
else
{
GD.PrintErr("Failed to load script from 'res://Global.cs'.");
}
}
}
Preferred Solution: Using /root/Global (Recommended)
Instead of manually creating an instance of the Global script every time the game runs (which creates unnecessary complexity), use the autoloaded singleton.
Register the Global.cs file as an Autoload (Steps repeated for clarity):
Open your project settings: Project > Project Settings > Autoload.
Select Global.cs by path (res://Global.cs).
Add it with the name Global.
Access the Singleton in a Script:
Use GetNode<Global>("/root/Global") to fetch the singleton properly.
Example code using /root/Global:
csharp
using Godot;
public partial class RtsCamera : Camera2D
{
private Global _globalScript;
public override void _Ready()
{
// Get the autoloaded Global singleton
_globalScript = GetNode<Global>("/root/Global");
// Validate and debug
if (_globalScript != null)
{
GD.Print("Global singleton accessed successfully.");
}
else
{
GD.PrintErr("Failed to find Global singleton.");
}
}
}
TL;DR
Avoid using res://Global.cs to directly load a singleton.
The correct and only proper way to use autoloaded nodes is via /root/Global after registering the script in Project Settings > Autoload.
If you must dynamically load and instantiate a Global script, use GD.Load<CSharpScript>("res://Global.cs") and call .New() to manually create an instance (not recommended).
If you follow the autoload approach, you will fix the CS0030 and CS0246 errors. Let me know if you need further clarification!
Key Points:
GD.Load<CSharpScript>("res://Global.cs") loads the Global.cs script file as a CSharpScript.
globalScriptResource.New() creates a new instance of the Global class from the loaded script.
AddChild(_globalScript) adds the new instance of Global to the scene tree.
2. What is Happening Here?
In this approach, you:
Load the script like a typical resource (GD.Load).
Dynamically create an object from the loaded script using .New().
Manually add the newly created instance to your scene tree.
When to Use This Approach
Use Case: If you want to dynamically add multiple copies of Global or test loading your script dynamically.
Why It Is Not Ideal for Singletons: If Global.cs is supposed to manage global data and logic shared across your entire game, it should only have one instance, and registering it as an autoload singleton would be better (/root/Global).
3. Alternative (Recommended): Use Proper Autoload Pattern
Instead of dynamically loading and instantiating Global, you can register it as a singleton autoload.
Register Global as Autoload:
In Godot Editor, go to Project > Project Settings > Autoload.
Add the res://Global.cs file.
Name it Global.
Access Singleton from RtsCamera:
csharp
using Godot;
public partial class RtsCamera : Camera2D
{
private Global _globalScript;
public override void _Ready()
{
// Fetch the Global singleton from its autoload path
_globalScript = GetNode<Global>("/root/Global");
if (_globalScript != null)
{
GD.Print("Global singleton accessed successfully!");
}
else
{
GD.PrintErr("Failed to find the Global singleton.");
}
}
public override void _Process(double delta)
{
// Example usage of the autoloaded Global singleton
if (_globalScript != null)
{
GD.Print("IsBoxSelecting: " + _globalScript.IsBoxSelecting);
}
}
}
4. Key Differences Between the Two Approaches
Dynamic Loading (res://Global.cs)
Singleton Global (Recommended Autoload)
Manually loads and creates instances of Global dynamically.
Automatically creates and shares a single Global instance.
Multiple instances of Global can exist in the project.
Ensures a single, shared instance of Global is accessible.
Requires AddChild() to include in the scene tree.
Automatically lives in the runtime tree as /root/Global.
Use when you need multiple Global instances.
Use when Global is shared game-wide (common singleton setup).
Which One Should You Use?
Dynamically Load and Create (res://Global.cs): Use this pattern only if you need different instances of the same script, e.g. for an enemy AI or a complex game object generator.
Singleton Autoload (Recommended): If Global.cs represents something like a game state manager, managing global properties or logic shared across your game, you should use the singleton autoload. This keeps the design clean, efficient, and idiomatic to Godot.
Let me know if you have more questions about either approach!
How This Works:
GD.Load<CSharpScript>("res://Global.cs") loads the script file at runtime as a CSharpScript resource.
globalScriptResource.New() creates a new instance of the Global class dynamically.
AddChild(_globalScript) adds the new instance to the current scene tree so it becomes active in the game.
You can interact with the dynamically-created Global instance like any other node.
2. Singleton Autoload Approach (/root/Global)
This is the recommended way to use a singleton like Global in Godot. You register Global.cs as an autoload so that it is shared globally and doesn't need to be instantiated dynamically.
Global.cs (Singleton Script)
The Global.cs script for the singleton autoload is the same. Here it is again for completeness:
csharp
using Godot;
using System;
public partial class Global : Node2D
{
public bool IsBoxSelecting { get; set; } = false;
public override void _Ready()
{
GD.Print("Global singleton is ready!");
}
public void PrintTestMessage()
{
GD.Print("This message is coming from the Global singleton autoload!");
}
}
Register Global.cs as a Singleton
Open Godot Editor.
Navigate to Project > Project Settings > Autoload.
Click the Add button.
Select res://Global.cs in the file dialog.
Set the name to Global (case-sensitive) and click Add.
Now, the Global node lives in /root/Global and can be accessed from anywhere in the game.
RtsCamera.cs (Using Singleton Autoload)
csharp
using Godot;
public partial class RtsCamera : Camera2D
{
private Global _globalScript;
public override void _Ready()
{
// Fetch the singleton from its autoload path
_globalScript = GetNode<Global>("/root/Global");
if (_globalScript != null)
{
GD.Print("Global singleton accessed successfully!");
_globalScript.PrintTestMessage();
}
else
{
GD.PrintErr("Failed to find Global singleton.");
}
}
public override void _Process(double delta)
{
if (_globalScript != null)
{
GD.Print("IsBoxSelecting: " + _globalScript.IsBoxSelecting);
}
}
}
How This Works:
The autoload system ensures that Global is automatically available globally under the path /root/Global.
You fetch the Global instance with GetNode<Global>("/root/Global").
The Global instance is already live and shared across the entire project.
3. Which Approach Should You Use?
Use Case
Dynamic Loading (res://Global.cs)
Singleton Autoload (/root/Global)
You need multiple instances of the script
✅ Yes
❌ Not suitable for multiple instances
One shared instance across the game
❌ No
✅ Perfect for shared global data or logic
Easier access project-wide
❌ Requires manual instantiation
✅ Automatically available under /root/Global
Complex game object logic
✅ Dynamic instantiation is better for diversity
❌ Use separate nodes, not the singleton itself.
Final Recommendation:
If your Global.cs manages shared game-wide logic (like game settings or selected units), go with Singleton Autoload. If you need to dynamically generate unique instances of Global for specific game objects, use the Dynamic Loading approach.
Both approached are fully implemented here—choose the one that best matches your needs. Let me know if you have further questions!
private Vector2 _mousePos = Vector2.Zero;
private Vector2 _mousePosGlobal = Vector2.Zero;
private Vector2 _start = Vector2.Zero;
private Vector2 _startV = Vector2.Zero;
private Vector2 _end = Vector2.Zero;
private Vector2 _endV = Vector2.Zero;
private bool _isDragging = false;
private Vector2 _targetPosition = Vector2.Zero;
private Panel _box;
private Area2D _selectionBox;
private Global _globalScript; // Reference to the autoload script
public override void _Ready()
{
_targetPosition = Position;
_box = GetNode<Panel>("../UI/Panel");
_selectionBox = GetNode<Area2D>("../Unit/Area2D");
_globalScript = (Global)GD.Load("res://Global.cs"); // Or fetch from autoloads if registered in Settings
}
public override void _Process(double delta)
{
HandlePanning((float)delta);
HandleZooming();
ProcessSelectArea();
Position = Position.Lerp(_targetPosition, InterpolationSpeed * (float)delta);
}
private void ProcessSelectArea()
{
if (Input.IsActionJustPressed("select_unit"))
{
_start = _mousePosGlobal;
_startV = _mousePos;
_isDragging = true;
_globalScript.IsBoxSelecting = true; // Flag for rectangle selection
}
if (_isDragging)
{
_end = _mousePosGlobal;
_endV = _mousePos;
DrawArea();
}
if (Input.IsActionJustReleased("select_unit"))
{
if (_startV.DistanceTo(_mousePos) > 20)
{
_end = _mousePosGlobal;
_endV = _mousePos;
_isDragging = false;
DrawArea(false);
_globalScript.OnAreaSelected(_start, _end);
}
else
{
_end = _start;
_isDragging = false;
DrawArea(false);
_globalScript.CheckUnitSelection(_mousePosGlobal);
}
_globalScript.IsBoxSelecting = false; // End rectangle selection
}
}
public override void _Input(InputEvent @event)
{
if (@event is InputEventMouse mouseEvent)
{
_mousePos = mouseEvent.Position;
_mousePosGlobal = GetGlobalMousePosition();
}
}
private void DrawArea(bool enable = true)
{
_box.Size = new Vector2(Math.Abs(_startV.X - _endV.X), Math.Abs(_startV.Y - _endV.Y));
var pos = new Vector2(
MathF.Min(_startV.X, _endV.X),
MathF.Min(_startV.Y, _endV.Y)
);
_box.Position = pos;
_box.Size *= enable ? 1 : 0;
}
private void HandlePanning(float delta)
{
var moveDir = Vector2.Zero;
var mousePos = GetViewport().GetMousePosition();
var viewportSize = GetViewport().GetVisibleRect().Size;
if (mousePos.X <= EdgeMargin)
moveDir.X -= 1;
else if (mousePos.X >= viewportSize.X - EdgeMargin)
moveDir.X += 1;
if (mousePos.Y <= EdgeMargin)
moveDir.Y -= 1;
else if (mousePos.Y >= viewportSize.Y - EdgeMargin)
moveDir.Y += 1;
if (Input.IsActionPressed("ui_left") || Input.IsActionPressed("ui_pan_left"))
moveDir.X -= 1;
if (Input.IsActionPressed("ui_right") || Input.IsActionPressed("ui_pan_right"))
moveDir.X += 1;
if (Input.IsActionPressed("ui_up") || Input.IsActionPressed("ui_pan_up"))
moveDir.Y -= 1;
if (Input.IsActionPressed("ui_down") || Input.IsActionPressed("ui_pan_down"))
moveDir.Y += 1;
_targetPosition += moveDir * PanSpeed * delta;
}
private void HandleZooming()
{
if (Input.IsActionJustPressed("ui_zoom_in"))
{
Zoom /= 1.1f;
if (Zoom.X < ZoomInLimit.X)
Zoom = ZoomInLimit;
}
if (Input.IsActionJustPressed("ui_zoom_out"))
{
Zoom *= 1.1f;
if (Zoom.X > ZoomOutLimit.X)
Zoom = ZoomOutLimit;
}
}
public void CheckUnitSelection(Vector2 globalMousePosition)
{
_selectionBox.GlobalPosition = globalMousePosition;
_selectionBox.CallDeferred("select_units_in_box");
}
}
using Godot;
using System;
public partial class CameraController : Camera2D
{
[Export] public float Speed = 20.0f;
[Export] public float PanSpeed = 1000.0f;
[Export] public Vector2 ZoomInLimit = new Vector2(0.5f, 0.5f);
[Export] public Vector2 ZoomOutLimit = new Vector2(2.0f, 2.0f);
[Export] public int EdgeMargin = 20;
[Export] public float InterpolationSpeed = 25.0f;
private Vector2 _mousePos = Vector2.Zero;
private Vector2 _mousePosGlobal = Vector2.Zero;
private Vector2 _start = Vector2.Zero;
private Vector2 _startV = Vector2.Zero;
private Vector2 _end = Vector2.Zero;
private Vector2 _endV = Vector2.Zero;
private bool _isDragging = false;
private Vector2 _targetPosition = Vector2.Zero;
private Panel _box;
private Area2D _selectionBox;
private Global _globalScript; // Reference to the singleton Global
public override void _Ready()
{
// Set the initial target position to the Camera2D's position
_targetPosition = Position;
// Get references to UI and selection box
_box = GetNode<Panel>("../UI/Panel");
_selectionBox = GetNode<Area2D>("../Unit/Area2D");
// Correctly fetch the autoloaded Global singleton
_globalScript = GetNode<Global>("/root/Global");
if (_globalScript == null)
{
GD.PrintErr("Global singleton not found! Ensure it's registered in autoloads.");
}
else
{
GD.Print("Global singleton found and ready to use.");
}
}
public override void _Process(double delta)
{
HandlePanning((float)delta);
HandleZooming();
ProcessSelectArea();
Position = Position.Lerp(_targetPosition, InterpolationSpeed * (float)delta);
}
private void ProcessSelectArea()
{
if (Input.IsActionJustPressed("select_unit"))
{
_start = _mousePosGlobal;
_startV = _mousePos;
_isDragging = true;
if (_globalScript != null) _globalScript.IsBoxSelecting = true; // Update flag in Global
}
if (_isDragging)
{
_end = _mousePosGlobal;
_endV = _mousePos;
DrawArea();
}
if (Input.IsActionJustReleased("select_unit"))
{
if (_startV.DistanceTo(_mousePos) > 20)
{
_end = _mousePosGlobal;
_endV = _mousePos;
_isDragging = false;
DrawArea(false);
if (_globalScript != null) _globalScript.OnAreaSelected(_start, _end);
}
else
{
_end = _start;
_isDragging = false;
DrawArea(false);
if (_globalScript != null) _globalScript.CheckUnitSelection(_mousePosGlobal);
}
if (_globalScript != null) _globalScript.IsBoxSelecting = false; // End rectangle selection
}
}
public override void _Input(InputEvent @event)
{
if (@event is InputEventMouse mouseEvent)
{
_mousePos = mouseEvent.Position;
_mousePosGlobal = GetGlobalMousePosition();
}
}
private void DrawArea(bool enable = true)
{
_box.Size = new Vector2(Math.Abs(_startV.X - _endV.X), Math.Abs(_startV.Y - _endV.Y));
var pos = new Vector2(
MathF.Min(_startV.X, _endV.X),
MathF.Min(_startV.Y, _endV.Y)
);
_box.Position = pos;
_box.Size *= enable ? 1 : 0;
}
private void HandlePanning(float delta)
{
var moveDir = Vector2.Zero;
var mousePos = GetViewport().GetMousePosition();
var viewportSize = GetViewport().GetVisibleRect().Size;
if (mousePos.X <= EdgeMargin)
moveDir.X -= 1;
else if (mousePos.X >= viewportSize.X - EdgeMargin)
moveDir.X += 1;
if (mousePos.Y <= EdgeMargin)
moveDir.Y -= 1;
else if (mousePos.Y >= viewportSize.Y - EdgeMargin)
moveDir.Y += 1;
if (Input.IsActionPressed("ui_left") || Input.IsActionPressed("ui_pan_left"))
moveDir.X -= 1;
if (Input.IsActionPressed("ui_right") || Input.IsActionPressed("ui_pan_right"))
moveDir.X += 1;
if (Input.IsActionPressed("ui_up") || Input.IsActionPressed("ui_pan_up"))
moveDir.Y -= 1;
if (Input.IsActionPressed("ui_down") || Input.IsActionPressed("ui_pan_down"))
moveDir.Y += 1;
_targetPosition += moveDir * PanSpeed * delta;
}
private void HandleZooming()
{
if (Input.IsActionJustPressed("ui_zoom_in"))
{
Zoom /= 1.1f;
if (Zoom.X < ZoomInLimit.X)
Zoom = ZoomInLimit;
}
if (Input.IsActionJustPressed("ui_zoom_out"))
{
Zoom *= 1.1f;
if (Zoom.X > ZoomOutLimit.X)
Zoom = ZoomOutLimit;
}
}
public void CheckUnitSelection(Vector2 globalMousePosition)
{
_selectionBox.GlobalPosition = globalMousePosition;
_selectionBox.CallDeferred("select_units_in_box");
}
}
Fix Summary
You cannot use GD.Load("res://Global.cs") to fetch singleton instances. Instead, fetch the singleton from the scene tree with:
csharp
_globalScript = GetNode<Global>("/root/Global");
Ensure Global.cs is registered in Project Settings > Autoload with the name Global. This makes it available globally.
Example of Global.cs
Here’s the expected singleton class Global:
csharp
using Godot;
using System;
public partial class Global : Node2D
{
public bool IsBoxSelecting { get; set; } = false;
public override void _Ready()
{
GD.Print("Global singleton is ready!");
}
public void OnAreaSelected(Vector2 start, Vector2 end)
{
GD.Print($"Selection Area: {start} to {end}");
// Add your logic here
}
public void CheckUnitSelection(Vector2 position)
{
GD.Print($"Checking unit at position: {position}");
// Add your single-click selection logic here
}
}
Now, everything should work correctly with full functionality. Let me know if you need further assistance!
}
using Godot;
using System;
using System.Collections.Generic;
public partial class Global : Node2D
{
public List<Node2D> Units { get; private set; } = new List<Node2D>();
public bool IsBoxSelecting { get; set; } = false; // Flag for rectangle selection
private bool _singleClickSelection = false; // Flag for single-click selection
private Timer _deselectionTimer;
private Control _uiControl; // Reference to the UI Control node
public override void _Ready()
{
GD.Print("Global singleton is ready!");
// Initialize rectangle selection deselection Timer
_deselectionTimer = new Timer();
_deselectionTimer.WaitTime = 0.2f;
_deselectionTimer.OneShot = true;
AddChild(_deselectionTimer);
_deselectionTimer.Timeout += OnDeselectionTimeout;
// Load and instantiate the UI scene
var uiScene = GD.Load<PackedScene>("res://Scenes/UI.tscn");
if (uiScene != null)
{
var uiInstance = uiScene.Instantiate();
AddChild(uiInstance);
// Get the "Control" node from the UI instance
_uiControl = uiInstance.GetNode<Control>("Control"); // Adjust path if necessary
}
GetUnits();
}
private void GetUnits()
{
Units.Clear();
foreach (var unit in GetTree().GetNodesInGroup("units"))
{
if (unit is Node2D unitNode)
{
Units.Add(unitNode);
if (unitNode.HasMethod("Init"))
{
unitNode.Call("Init", this); // Initialize units with a reference to this script
}
}
}
}
public void SelectUnit(Node2D unit)
{
if (!IsBoxSelecting && !_singleClickSelection)
{
DeselectAllUnits(unit); // Ensure all other units are deselected, except this one
}
if (unit.HasMethod("SetSelected"))
{
unit.Call("SetSelected", 1); // Select the unit
}
_singleClickSelection = true;
_deselectionTimer.Start(); // Start delay timer for toggling deselection
// Update the UI if `_uiControl` exists
if (_uiControl != null)
{
_uiControl.Call("set_selected_unit", unit);
}
}
public void DeselectAllUnits(Node2D excludeUnit = null)
{
foreach (var unit in Units)
{
if (unit.HasMethod("SetSelected") && unit != excludeUnit)
{
unit.Call("SetSelected", 0); // Deselect the unit
}
}
}
public void OnAreaSelected(Vector2 start, Vector2 end)
{
GD.Print($"Selecting units in area from {start} to {end}");
Rect2 area = new Rect2(start, end - start).Abs();
foreach (var unit in Units)
{
if (unit is Node2D unitNode && area.HasPoint(unitNode.Position))
{
if (unitNode.HasMethod("SetSelected"))
{
unitNode.Call("SetSelected", 1); // Select unit
}
}
}
}
public void CheckUnitSelection(Vector2 globalMousePosition)
{
GD.Print($"Checking selection for unit at {globalMousePosition}");
foreach (var unit in Units)
{
if (unit is Node2D unitNode)
{
// Assumes each unit has `Position` and `Scale` for bounding box checking
Rect2 unitRect = new Rect2(
unitNode.Position - (unitNode.Scale / 2), // Calculate top-left corner
unitNode.Scale
);
if (unitRect.HasPoint(globalMousePosition))
{
if (unitNode.HasMethod("SetSelected"))
{
unitNode.Call("SetSelected", 1); // Select the unit
}
}
else
{
if (unitNode.HasMethod("SetSelected"))
{
unitNode.Call("SetSelected", 0); // Deselect the unit
}
}
}
}
}
private void OnDeselectionTimeout()
{
_singleClickSelection = false;
}
}
Explanation of Changes
Added OnAreaSelected(Vector2 start, Vector2 end):
Handles rectangle ("box") selection of units by calculating a Rect2 from the given start and end positions. All units within this area are selected.
Operates on all units in the Units list, assuming they exist in the "units" group.
Handles single-click selection by checking if a unit's position (via its Rect2 bounding box) contains the click point.
Selects the clicked unit and deselects all others.
Assumptions:
Every unit in the Units list has a Position and Scale property.
These units also contain a SetSelected(int) method that allows marking them as selected (1) or deselected (0).
Helper Methods:
DeselectAllUnits(Node2D excludeUnit = null): Handles the deselection logic for all units except the one being selected.
_OnDeselectionTimeout: A small delay before deselection to ensure smooth interaction during single-click or rectangle selection.
How Everything Works Together
In your CameraController class, these methods are used for interaction:
OnAreaSelected: Called when dragging ends for rectangle selection.
CheckUnitSelection: Called when a single click is detected.
Here is how these align with your CameraController.cs logic:
Example in CameraController.cs
csharp
if (_startV.DistanceTo(_mousePos) > 20)
{
// Rectangle ("Box") Selection
_globalScript.OnAreaSelected(_start, _end);
}
else
{
// Single Click Selection
_globalScript.CheckUnitSelection(_mousePosGlobal);
}
These calls now properly reference methods defined in the updated Global class.
Things to Verify
Add units to the "units" group in the Godot Editor (for GetTree().GetNodesInGroup("units") to work).
Ensure that each unit properly implements the SetSelected(int) method (used to toggle selection state).
Verify that input events (select_unit) are defined correctly in the Input Map.
After making these changes, your CameraController script should work seamlessly with the updated Global class. Let me know if you have further issues or need additional clarification!