Unity使用puerTS使用typescript 您所在的位置:网站首页 typescript主要用途 Unity使用puerTS使用typescript

Unity使用puerTS使用typescript

2023-07-04 23:36| 来源: 网络整理| 查看: 265

puerts即为普洱TS,腾讯开源的ts热更方案.项目github:https://github.com/Tencent/puerts 准备工作:Unity 2021.3.25f1 nodejs v16.13.1 1.下载puerts 地址:https://github.com/Tencent/puerts/releases 版本随便选. 解压好,将puerts文件夹放到assets/ 下.如图:在这里插入图片描述 2.生成代码.在这里插入图片描述 3.在assets下创建ts文件夹用来存放ts源码.文件夹名字随便起,我这里叫 TsProject.然后执行命令:

npm init -y npm i typescript -D

创建tsconfig.json文件.这个主要是ts的配置.

{ "compilerOptions": { "target": "esnext", "module": "commonjs", "sourceMap": true, "noImplicitAny": true, "typeRoots": [ "../Puerts/Typing", "../Gen/Typing", "./node_modules/@types" ], "outDir": "output" } }

package.json,这里主要是修改scripts指令.build与postbuild.

{ "name": "tsproject", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "tsc -p tsconfig.json", "postbuild": "node copyJsFile.js output ../Resources" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "typescript": "^5.1.6" } }

copyJsFile.js文件下载地址:https://github.com/chexiongsheng/puerts_unity_demo/blob/master/projects/0_Basic_Demo/TsProj/copyJsFile.js 重点来了,main.ts

import { System, UnityEngine } from 'csharp' UnityEngine.Debug.Log('Hello World'); let obj: UnityEngine.GameObject = new UnityEngine.GameObject("testObject"); obj.transform.position = new UnityEngine.Vector3(10, 2, 23);

完成后:tsproject文件夹的样子是下面这样的: 在这里插入图片描述 现在开始编译ts. 使用package.json的scripts下的 build 指令.然后在使用 postbuild指令. 完成后可以看到Resources文件夹里有生成的代码.如果没创建Resources,需要手动创建一下. 4.c#中处理沟通js的逻辑. 在这里插入图片描述 Require.cs文件挂载到灯上或者其他物体上.

using System.Collections; using System.Collections.Generic; using UnityEngine; using Puerts; public class Require : MonoBehaviour { JsEnv jsEnv; // Start is called before the first frame update void Start() { jsEnv = new JsEnv(); jsEnv.Eval(@"require('main')");//这里会从Resources中加载对应的main.js.txt文件 } // Update is called once per frame void Update() { } private void OnDestroy() { jsEnv.Dispose(); } }

然后开始运行编辑器:打出了log,并且生成了空物体. 在这里插入图片描述 其实还有一个更简单的测试js的脚本,不需要刚才的ts比较麻烦的创建.JsCallCs.cs

using System.Collections; using System.Collections.Generic; using UnityEngine; using Puerts; public class JsCallCs : MonoBehaviour { JsEnv jsEnv; // Start is called before the first frame update void Start() { jsEnv = new JsEnv();//下面是相当于拿到js的代码 jsEnv.Eval(@" const CS=require('csharp'); let gameObject=new CS.UnityEngine.GameObject('testObject'); CS.UnityEngine.Debug.Log(gameObject.name); "); } // Update is called once per frame void Update() { } private void OnDestroy() { jsEnv.Dispose(); } }

另:此处还有一个坑,就是在copyJsFile.js中,编译ts的时候,在Resources下是main.js,但是c#需要的是main.js.txt文件,也就是一个字符串.会报错,错误代码58,找不到mian.解决办法: 在这里插入图片描述 放开此处的注释,然后在重新编译ts即可.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有