Load Json from a path in the project


#1

I’m rewriting a unity project in play canvas and have some very basic questions. I have uploaded a file in Assets/Data/Settings.json and I’d like to load it. The documentation tells me I should run app.assets.find(‘Settings’).resource; which seems counter productive since I know where the file is and the file is not a “resource”. How do I simply load the file from a path in the project?


#2

Hi @noah_mizrahi,

This is much easier working in the editor, you have to use script attributes to reference any kind of asset in your script:

MyScript.attributes.add('jsonFile', { type: 'asset', assetType: 'json' });

You can read here more:

https://developer.playcanvas.com/en/user-manual/scripting/script-attributes/


#3

Your code is still valid, it uses the assets name to find it in the asset registry and returns a pc.Asset.

The payload of the asset, in this case the JSON structure can be found in the resource property.

You can read about the pc.Asset class here:

https://developer.playcanvas.com/en/api/pc.Asset.html


#4

I see. The problem with script attributes is I don’t know how to make them accessible to other scripts. I’m trying to understand this framework and I’m not quite there yet.


#5

Good, let’s see how to do that, accessing script attributes from another script:

  1. First we need to figure out on which entity the script is attached to, if it is the same entity then that would be this.entity in your code. If it is not, then you will need to find that other entity and have it available on a variable:
var otherEntity = this.app.root.findByName('otherEntityName');
  1. As soon as you have the entity that you know holds the script in its script component (named for example myScript) then you access it using the dot notation:
// if it is attached on the same entity
var speed = this.entity.script.myScript.speed;

// if it is on another entity
speed = otherEntity.script.myScript.speed;

Indeed it isn’t straightforward initially, but as soon as you figure out the entity, script name and property name you can easily access it. Your best friend is the console and console.log() to understand how everything is being put in place by the engine.


#6

This post may help in understanding PlayCanvas and accessing different parts of an entity How to refer to different parts of the API while scripting