Skip to content

3.5 ‐ 02 Creating Elements

WhyTry313 edited this page Oct 23, 2023 · 9 revisions

Description

To explain GDScript's new keyword and its difference with JavaScript, i'll need to quote 🔗 this comment by p7f

new() is used to create a node from the class. Thats why you must call var img = Image.new(), cause on the contrary, you would be trying to assign Image built in data type to the variable img. Why you do not call new in Vector2 then? Cause, acording to docs Vector2 is also a member function from the Vector2 built in type, that constructs a Vector2 object and returns it. So you dont call new because Vector2() is doing it for you. When you write var vec = Vector2(10,20) you are executing Vector2() function. Image does not have similar member function, so you must call new.



With this ECMAScript module, all elements from the Godot API are classes, meaning you'll need to always use the new keyword followed by godot.ClassName to create an element (exception made for the constants)



Syntax

    new Class:ClassName(arguments?)


How to use it with examples

A brief yet explanatory way to hilight the differences

# GDScript
var center = Vector2(0,5)
var image = Image.new()
// JavaScript
export default myClass extends godot.Node() {
    constructor() {
        this.center = new godot.Vector2(0,5);
        this.image = new godot.Image();
    }
}



Advanced use

Full list of new godot.TYPE

Here's the list of the 🔴 701 elements 🔴 you can create using
new godot.TYPE you can find in 🔗 Godot's 3.5 API Documentation
⚠️ Please understand by clicking here this will show a very big list.



Clone this wiki locally