stringcocoscreator

How to get string from .txt file and fill it to Label String in Cocos Creator


I want to fill Label String with text from sometext.txt file in Cocos Creator.

I did this:

@property({type:Node})
cptxt = null;
.
.
.
this.copyrightText = jsb.fileUtils.getStringFromFile('Text/copyright.txt');
this.cptxt.string = this.copyrightText;

I filled cptxt with the label on the Scene. But it doesn't works. The Label String is not filled. I run on Android


Solution

  • You can get the text asset using "resources.load()" then using ".toString()" to get a string representation of the text object.

    P.S. To use the "resources.load()" you have to create a folder named "resources" under assets folder in your project directory then under "resources" you can create your sub folder "Text" and in that folder put your copyright.txt file

    Also type of cptxt property should be "Label" if you are trying to get the Label component's string property directly

    import {. . ., Label} from 'cc';
    
     @property({type:Label})
        cptxt: Label = null;
        .
        .
        .
    resources.load("Text/copyright", (err, textAsset) => {
        this.cptxt.string = textAsset.toString();;
        });