+1 vote

Hi all,

I am wondering if it is possible to load a script on an object and then (re?)load another script.

The scenario I am thinking is the following:

You have an area2d which reacts to some mouse input. Depending on variables (either global or local) you can get different "actions".

This is basically a description of making some adventure game verbs and interact with the said area2d. For example in a menu you could have a button for look and a button for push which will setup some variables and upon clicking the area2d object would load the look script or the push script.

I don't have any proof at the moment the last time I tried, I couldn't put the area2d to behave with the second script loaded (I'd assume it has something to do with .reload() method).

So anyone has something similar to share or any alternatives?

Godot version 3.4.4
in Engine by (72 points)

1 Answer

0 votes

Changing a script from code should be as simple as

 node.SetScript((Script)GD.Load("ScriptPath"));

However when you change a script the old reference becomes invalid and you can't access it anymore. To get a new reference with the changed script you should do this.

ulong objId = node.GetInstanceId();
node.SetScript((Script)GD.Load("ScriptPath"));
Node newNode = (Node)GD.InstanceFromId(objId);

(Code is in C#)

by (58 points)

That's very interesting, let me try to do this in gdscript and I'll come back for the tick!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.