This discussion was closed at the author’s request due to a change in approach. Therefore, if you came here looking for a solution to a problem, you won’t find one here. The text below is included here because the discussion will be closed in a month. My apologies to everyone who ended up here after searching for a solution to a problem.
Godot Version 4.7, C#
The problem is that, although you can simply attach a weapon node to a player, this will cause huge problems down the future. Next, I’ll describe the model I tried:
Apparently, he started by creating an abstract class:
using Godot;
public abstract partial class Gun : Node2D
{
[Export] private PackedScene _projectileScene;
[Export] public Key ButtonForUse;
public abstract void Shoot();
public abstract void SpawnProjectile();
}
The code for the realization this class doesn’t matter, because the problem was specifically with the implementation of the call logic.
After i wrote the following code:
using Godot;
using System;
using System.Linq;
public partial class GunInventory : Node
{
[Export] private Godot.Collections.Array<Gun> _weaponList;
private Gun _activeWeapon;
private Gun _newActiveWeapon;
public override void _UnhandledInput(InputEvent @event)
{
if (@event is not InputEventKey eventKey || !eventKey.Pressed || eventKey.Echo) return;
if (eventKey.Keycode < Key.Key1 || eventKey.Keycode > Key.Key9) return;
_newActiveWeapon = _weaponList.FirstOrDefault(weapon => weapon.ButtonForUse == eventKey.Keycode);
if (_newActiveWeapon == null) return;
_activeWeapon = _newActiveWeapon;
}
public void EquipWeapon()
{
}
}
Why this logic? Because I think that if you just assign weapons to a player model, they’ll all be activated at the same time. The idea was to create the necessary one when needed, and then it would decide for itself what to do next. (There is no script responsible for adding a node to a player, because the script stopped working before the node-adding feature was implemented) However:
- If it’s a `gun` list, we’ll create a virtual weapon that exists only in the code. In other words, it’s not linked to the `tscn` scene in any way.
- Why not just create a tscn (This is called packaged scenes) list instead? That would solve the first problem, but it would create another one — C# won’t let the code run because it can’t guarantee that `gun` will contain `ButtonToUse`, so the code won’t execute.
I tried to figure out what was wrong, and as I understood it, you can’t accesstscndirectly because it’s just a drawing, not an actual node. But then I don’t know how to initialize it correctly.
If I’m just misunderstanding how to work with Node, please provide a link to the documentation explaining how it works—I’d appreciate it. It’s just that when I tried it, I figured Node was meant to build an object and then use it (Composition), but it’s somehow very difficult to work with them when there are lists of them, so maybe I’m doing something wrong.
I’d appreciate any help.