Home | Documentation | Atomic Chat | Github

[Solved] Loading a Tiled map through C# code?


#1

Hi People of Atomic,

Been using the engine for a few weeks and loving the simplicity and elegance. Definitely looking forward to seeing it grow.

My first question is as follows:
I’m able to load a tiled map through the atomic editor, but can’t figure out how to do it from code. Right now my code looks like this:

TileMap2D mapComponent = new TileMap2D();
mapComponent.SetTmxFile(new TmxFile2D().Load( WHAT GOES HERE? ));
Node mapNode = new Node();
mapNode.AddComponent(mapComponent);

The load method accepts (Deserializer source), but how to I get the actual .tmx file in there? Any tips greatly appreciated.
Cheers.


#2

The deserializer probably means it’s a Resource, in not-so-many (or clear) words. See if this code gets you further.

using AtomicEngine;
using AtomicPlayer;

public class AtomicMain : AppDelegate
{
    public override void Start()
    {
        Scene myscene = AtomicNET.GetSubsystem<Player>().LoadScene("Scenes/Scene.scene");
	Node mapNode = new Node();
	TileMap2D mapComponent = mapNode.CreateComponent<TileMap2D>();
	mapComponent.TmxFile = GetSubsystem<ResourceCache>().GetResource<TmxFile2D>("Scenes/isometric_grass_and_water.tmx");
	myscene.AddChild(mapNode);
    }

}

#3

Thanks Jim.
It seems to be loading the tmx file now, but I get a System.AccessViolationException when trying to assign the file to the component.

Node mapNode = new Node();
TileMap2D mapComponent = mapNode.CreateComponent<TileMap2D>();
TmxFile2D tmxFile = GetSubsystem<ResourceCache>().GetResource<TmxFile2D>("Maps/map1.tmx");
mapComponent.TmxFile = tmxFile; // <-- Errors out here

The last line in my code throws the error.
System.AccessViolationException: ‘Attempted to read or write protected memory. This is often an indication that other memory is corrupt.’

If I try running through the editor, I get this error in the log:
ERROR: at AtomicEngine.TileMap2D.csb_Atomic_TileMap2D_SetTmxFile_2958(IntPtr self, IntPtr tmxFile)

When debugging in VS, I can see that the TmxFile2D object has 4 layers, which is how many my map has, so everything up till the last line seems to be working fine.

image

Any ideas?


#4

My experience has been, the other files the tmx file needs (pngs, etc) must be in the same directory as the .tmx file or bad things happen. bad things.


#5

Solved by creating a new project and trying again.
Not sure why it wasn’t working in my old project.
Thanks for the help.