Godot Version
4.4
Question
Best way to get control after SetScript destroys/changes it.
I’m running a script after applying it to a newly created Button. This is how I got it to work:
Button button = new Button();
_kitSelectBox.AddChild(button);
// get the Id
var id = button.GetInstanceId();
button.SetScript(ResourceLoader.Load(_kitButtonPath));
// because button is now invalid due to SetScript creating a new instance
// use id to find it again
foreach (var child in _kitSelectBox.GetChildren())
{
if (child.GetInstanceId() == id)
{
button = (Button)child;
break;
}
}
// now get the script
kit_button kitButton = (kit_button)button;
// and call method
kitButton.SetKit(kit);
It looks like there’s 2 things I wish this did better:
- new Button() could accept the script resource in the constructor
- or SetScript() could return the new Control
Or am I just not finding the better way that already exists to do this?
… The instance is in your example doesnt change so i would assume your object doesnt change.
If you read what set script does, it will change the node but not destroy it, but i dont think you need to go get it again since you already have a reference.
What happens if you just cast the button into the new type after setscript? I.e. comment out the id search.
The way its typically done is you create a scene with the script attached and initiate it. Or, if its just a single node script like this example, just call new on the loaded script and it will return the node with the attached script for you.
kit_button kitButton = new kit_button();
_kitSelectBox.AddChild(kitButton);
kitButton.SetKit(kit);
That’s it! Thanks!
Wow, did I do it the hard way!
But I learned a bunch about SetScript.
What happens if you just cast the button into the new type after setscript?
To be complete here, after you do SetScript, the object that your variable is pointing at gets flagged with ObjectDisposedException and is unusable. After SetScript, you MUST reacquire it if you want to do anything further.
1 Like