using Godot;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public partial class MainScene : Node2D
{
AudioStreamPlayer player = new();
AudioStreamPlayer player1 = new();
Dictionary<string,AudioStream> audiomapper= new();
Dictionary<string, AudioStream> audiomapper1 = new();
public override void _Ready()
{
this.Set("SceneName", "MainScene");
audiomapper["bullet1"] = GD.Load<AudioStream>("res://Audio/BU.mp3");
audiomapper["bgm1"] = GD.Load<AudioStream>("res://Audio/BU.ogg");
AddChild(player);
audiomapper1["bullet1"] = GD.Load<AudioStream>("res://Audio/BU.mp3");
audiomapper1["bgm1"] = GD.Load<AudioStream>("res://Audio/BU.ogg");
AddChild(player1);
}
public void PlayAudio(string name)
{
player.Stream = audiomapper[name];
player.Play();
}
public void PlayAudio1(string name)
{
player1.Stream = audiomapper1[name];
player1.Play();
}
public override void _Process(double delta)
{
}
}
上面是我的主场景脚本
using Godot;
using System;
public partial class Player : Sprite2D
{
private double speed = 100;
public PackedScene bulletPrefab;
private MainScene Main_scene;
public override void _Ready()
{
bulletPrefab = GD.Load<PackedScene>("res://Prefab/bullets.tscn");
Main_scene = this.GetTree().CurrentScene as MainScene;
}
public override void _Process(double delta)
{
double movementdouble = speed * delta;
float movement = (float)movementdouble;
if (Input.IsActionPressed("ui_right"))
{
Position += new Vector2(movement, 0);
}
if (Input.IsActionPressed("ui_left"))
{
Position += new Vector2(-movement, 0);
}
if (Input.IsActionPressed("ui_up"))
{
Position += new Vector2(0, -movement);
}
if (Input.IsActionPressed("ui_down"))
{
Position += new Vector2(0, movement);
}
if (Input.IsActionJustPressed("fire"))
{
Main_scene.PlayAudio1("bullets");
var bullet = bulletPrefab.Instantiate() as Node2D;
GetParent().AddChild(bullet);
bullet.Position = Position;
}
}
}
Main_scene = this.GetTree().CurrentScene as MainScene;
I think, you can try to use that code instead:
Main_scene = GetNode<MainScene>("/root/YourRootNode");
# At '/root' path contains Window
# At '/root/YourRootNode' path contains a first node on scene
# So write your Node name with MainScene class after /root/
Try using GD.print() to output the results from both options and compare them.
Edited: I tried to compare at my project and both results are the same, but apparently something is not quite right in your case. Still, I’m glad you did it.