![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | a_neobum |
Hello!
I’m a beginner who’s feeling really stupid right now.
I have a scene HexTile (Node2D) with a child Label (Label), added through the scene editor.
I have another scene Board (Node). Board is meant to be the main scene.
Each scene has a C# script.
Board instances, and adds as children, several HexTile scenes through its script and stores them in a collection.
It then attempts to access the Label of each HexTile and set its text.
The Label is not found; the debugger claims “object reference not set to an instance of an object”.
The relevant code looks something like this:
public class Board : Node
{
private HexTile[] _hexes;
public override void _Ready()
{
_hexes = new HexTile[10];
for (int i = 0; i < 10; i++)
{
var hex = new HexTile();
AddChild(hex);
hex.GetNode<Label>("Label").SetText("test");
}
}
}
I’ve confirmed that the HexTiles get properly added as child scenes of Board as, without the call to Label, they get placed and drawn properly.
I’ve confirmed that Label is properly added to HexTile, as it displays properly when running the HexTile scene in isolation, and accessing Label and editing its text works.
I get the same error if I move the Label-accessing line to the script of HexTile and run the project with Board as the main scene. (HexTile still runs fine in isolation.)
I cannot, for the life of me, figure out what I’m doing wrong here. Please help me!
Thank you in advance!
Is your Label a part of the Hex scene, or dynamically instantiated from the Hex _ready()?
_ready is almost definitely not called by the time you call hex.GetNode. I haven’t dug into when _ready gets called, but I’ve encountered similar problems when duplicating nodes - where AddChild doesn’t synchronously trigger _ready on the child, and instead it was getting called (I assume) on the next frame.
MitchReidNZ | 2020-02-03 04:08