How to create a GridMap from GDScript given the MeshLibrary as .tres

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By abelgutierrez99

Hello, I’m new to Godot
I want to create a GridMap using GDScript from a MeshLibrary as .tres. This is what I did, but it doesn’t work

extends Node


func _ready():
    pass


class Scenario extends Spatial:


    # number of hexagons in the x direction
    var xdim : int
    # number of hexagons in the z direction
    var zdim : int

    # Meshlib for tiles
    var meshLib : MeshLibrary
    # GridMap for tiles
    var gridMap : GridMap


    func _init(xdim, zdim):
	
	    self.xdim = xdim
	    self.zdim = zdim
	
	    self.meshLib = MeshLibrary.new("res://Assets/MapTiles/MapTiles.tres")
	
	    self.gridMap = GridMap.new()
	    self.gridMap.mesh_library = self.meshlib
:bust_in_silhouette: Reply From: Lopy

class is misleading, as it does not mean exactly the same thing as in other languages. Every .gd file is a class. While you could access them by resource path, you give the ones that are referenced outside a legible name using class_name Scenario.
class is used to define private (helper) classes, to be used inside your primary one.
Notably, here your class is defined only as a Node, with an empty _ready(). Either instantiate your helper class, or merge them back together (by renaming class to class_name and dropping the indent).

If your MeshLibrary is in file form, you use meshlib = preload(res://Assets/MapTiles/MapTiles.tres). Resources are only really loaded from disk once, with subsequent calls to load returning the cached instance. load also works, but preload has the advantage of loading the Resource along with the Script, avoiding a potential hickup when the scene is running, and the path is checked at spellcheck.

You define a GridMap, give a MeshLibrary full of Meshes, but you do not set any of the GridMap’s cells, meaning you won’t see if anything happened.

The instantiated GridMap is never added to the tree, meaning it cannot display anything. Use add_child() to add it as the daughter of some Node that is in the tree. Also note that any _init() are called when the object is instantiated, not added to the tree. To access the tree, you generally have to wait for your Node’s _ready() to be called.

Here is the official GridMap tutorial. I would recommend setting one up declaratively first, to get a good understanding of how they work. Note that the method described to generate a MeshLibrary is not really suited for hexagons. You will likely want to make your MeshLibrarys by code. To make previews this way, you will seek get_editor_interface().make_mesh_previews() (only work inside a tool Script).

When you said “you will likely want to make your MeshLibrarys by code”, do you mean to create a scene with all the meshes and access them as child nodes by code?

abelgutierrez99 | 2020-12-25 16:40