Needle Engine
  • README
  • Code Of Conduct
  • HOW TO
  • documentation
    • SUMMARY
    • _backlog-mermaid
    • _backlog
    • _meta-test
    • Automatic Component Generation
    • Needle Core Components
    • How To Debug
    • Deployment and Optimization
    • embedding
    • Everywhere Actions
    • Example Projects ✨
    • Exporting Assets, Animations, Prefabs, Materials, Lightmaps...
    • Questions and Answers (FAQ) 💡
    • Feature Overview
    • This page has been moved: continue here
    • getting-started
    • Frameworks, Bundlers, HTML
    • index
    • Additional Modules
    • Networking
    • Needle Engine Project Structure
    • Samples Projects
    • Scripting Examples
    • Creating and using Components
    • Live
    • Live
    • About
    • Live
    • Live
    • Live
    • Live
    • Support, Community & AI
    • Technical Overview
    • Testimonials
    • Testing on local devices
    • Using Needle Engine directly from HTML
    • vision
    • VR & AR (WebXR)
    • blender
      • Needle Engine for Blender
    • cloud
      • Needle Cloud
    • custom-integrations
      • index
    • getting-started
      • Scripting Introduction for Unity Developers
      • Getting Started & Installation
      • Scripting in Needle Engine
    • reference
      • needle.config.json
      • <needle-engine> Configuration
      • @serializable and other decorators
    • three
      • index
    • unity
      • Editor Sync
      • Needle Engine for Unity
    • lang
      • de
        • 404
        • SUMMARY
        • Automatische Komponenten-Generierung
        • Needle-Kernkomponenten
        • Debugging
        • Bereitstellung und Optimierung
        • embedding
        • Everywhere Actions
        • Beispielprojekte ✨
        • Assets, Animationen, Prefabs, Materialien, Lightmaps exportieren...
        • Fragen und Antworten (FAQ) 💡
        • Funktionsübersicht
        • Diese Seite wurde verschoben: hier fortfahren
        • getting-started
        • Frameworks, Bundler, HTML
        • index
        • Zusätzliche Module
        • Netzwerkfunktionen
        • Needle Engine Projektstruktur
        • Beispielprojekte
        • Scripting Beispiele
        • Erstellen und Verwenden von Komponenten
        • Live
        • Live
        • Über
        • Live
        • Live
        • Live
        • Live
        • Support und Community
        • Technischer Überblick
        • Erfahrungsberichte
        • Testen auf lokalen Geräten
        • Needle Engine direkt aus HTML verwenden
        • vision
        • VR & AR (WebXR)
        • blender
          • Needle Engine für Blender
        • cloud
          • Needle Cloud
        • custom-integrations
          • index
        • getting-started
          • Einführung in das Scripting für Unity-Entwickler
          • Erste Schritte & Installation
          • Scripting in Needle Engine
        • reference
          • needle.config.json
          • <needle-engine> Konfiguration
          • @serializable und andere Decorators
        • three
          • index
        • unity
          • Editor Synchronisierung
          • Needle Engine für Unity
      • es
        • SUMMARY
        • Generación Automática de Componentes
        • Componentes principales de Needle
        • Cómo Depurar
        • Despliegue y optimización
        • embedding
        • Acciones Everywhere
        • Proyectos de Ejemplo ✨
        • Exportación de Assets, Animaciones, Prefabs, Materiales, Lightmaps...
        • Preguntas Frecuentes (FAQ) 💡
        • Resumen de Características
        • Esta página ha sido movida: continúe aquí
        • getting-started
        • Frameworks, Bundlers, HTML
        • index
        • Módulos Adicionales
        • Redes
        • Estructura de Proyecto de Needle Engine
        • Proyectos de ejemplo
        • Ejemplos de scripting
        • Crear y usar Components
        • En vivo
        • En Vivo
        • Acerca de
        • En vivo
        • En vivo
        • En vivo
        • En vivo
        • Soporte y Comunidad
        • Resumen técnico
        • Testimonios
        • Testing on local devices
        • Usando Needle Engine directamente desde HTML
        • vision
        • VR & AR (WebXR)
        • blender
          • Needle Engine para Blender
        • cloud
          • Needle Cloud
        • custom-integrations
          • index
        • getting-started
          • Introducción al Scripting para Desarrolladores de Unity
          • Primeros pasos e instalación
          • Scripting in Needle Engine
        • reference
          • needle.config.json
          • Configuración de <needle-engine>
          • @serializable y otros decoradores
        • three
          • index
        • unity
          • Editor Sync
          • Needle Engine para Unity
      • fr
        • SUMMARY
        • Génération automatique de composants
        • Composants principaux de Needle
        • Comment déboguer
        • Déploiement et Optimisation
        • embedding
        • Everywhere Actions
        • Exemples de Projets ✨
        • Exporter des Assets, des Animations, des Prefabs, des Matériaux, des Lightmaps...
        • Questions et Réponses (FAQ) 💡
        • Aperçu des fonctionnalités
        • Cette page a été déplacée : continuez ici
        • getting-started
        • Frameworks, Bundlers, HTML
        • index
        • Modules supplémentaires
        • Réseau
        • Structure du projet Needle Engine
        • Projets d'exemples
        • Exemples de Scripting
        • Créer et utiliser des Components
        • showcase-bike
        • En direct
        • À propos
        • En direct
        • Jouer
        • En direct
        • En direct
        • Support et Communauté
        • Vue d'ensemble technique
        • Témoignages
        • Tester sur les appareils locaux
        • Utiliser Needle Engine directement depuis HTML
        • vision
        • VR & AR (WebXR)
        • blender
          • Needle Engine pour Blender
        • cloud
          • Needle Cloud
        • custom-integrations
          • index
        • getting-started
          • Introduction au Scripting pour les Développeurs Unity
          • Premiers pas et installation
          • Scripting in Needle Engine
        • reference
          • needle.config.json
          • <needle-engine> Configuration
          • @serializable et autres décorateurs
        • three
          • index
        • unity
          • Synchronisation de l'Editor (Editor Sync)
          • Needle Engine pour Unity
      • hi
        • SUMMARY
        • कंपोनेंट का स्वतः जनरेशन
        • नीडल कोर कंपोनेंट्स
        • How To Debug
        • Deployment and Optimization
        • embedding
        • Everywhere Actions
        • उदाहरण प्रोजेक्ट ✨
        • एसेट, एनिमेशन, प्रीफैब, मटेरियल, लाइटमैप्स... को एक्सपोर्ट करना
        • प्रश्न और उत्तर (FAQ) 💡
        • सुविधा अवलोकन
        • यह पृष्ठ स्थानांतरित कर दिया गया है: यहां जारी रखें
        • getting-started
        • Frameworks, Bundlers, HTML
        • index
        • अतिरिक्त मॉड्यूल
        • नेटवर्किंग
        • Needle Engine प्रोजेक्ट स्ट्रक्चर
        • samples-and-modules
        • स्क्रिप्टिंग उदाहरण
        • कंपोनेंट बनाना और उपयोग करना
        • लाइव
        • लाइव
        • परिचय
        • लाइव
        • लाइव
        • लाइव
        • लाइव
        • समर्थन और समुदाय
        • तकनीकी अवलोकन
        • प्रशंसापत्र
        • Testing on local devices
        • HTML से सीधे Needle Engine का उपयोग करना
        • vision
        • VR & AR (WebXR)
        • blender
          • Needle Engine for Blender
        • cloud
          • Needle Cloud
        • custom-integrations
          • index
        • getting-started
          • Unity डेवलपर्स के लिए स्क्रिप्टिंग परिचय
          • आरंभ करना और इंस्टॉलेशन
          • Needle Engine में स्क्रिप्टिंग
        • reference
          • needle.config.json
          • <needle-engine> कॉन्फ़िगरेशन
          • @serializable and other decorators
        • three
          • index
        • unity
          • Editor Sync
          • Unity के लिए Needle Engine
      • ja
        • SUMMARY
        • 自動コンポーネント生成
        • Needleコアコンポーネント
        • デバッグの方法
        • デプロイと最適化
        • embedding
        • Everywhere Actions
        • サンプルプロジェクト ✨
        • アセット、アニメーション、Prefab、マテリアル、ライトマップなどのエクスポート
        • よくある質問(FAQ)💡
        • 機能概要
        • このページは移動しました: こちらからどうぞ
        • getting-started
        • フレームワーク、バンドラー、HTML
        • index
        • 追加モジュール
        • ネットワーキング
        • Needle Engineプロジェクトの構造
        • サンプルプロジェクト
        • スクリプティング例
        • Creating and using Components
        • ライブ
        • showcase-castle
        • 概要
        • ライブ
        • ライブ
        • ライブ
        • ライブ
        • サポートとコミュニティ
        • 技術概要
        • お客様の声
        • ローカルデバイスでのテスト
        • HTMLからNeedle Engineを直接使用する
        • vision
        • VR & AR (WebXR)
        • blender
          • Blender 用 Needle Engine
        • cloud
          • Needle Cloud
        • custom-integrations
          • index
        • getting-started
          • Scripting Introduction for Unity Developers
          • はじめに & インストール
          • Needle Engineでのスクリプティング
        • reference
          • needle.config.json
          • <needle-engine> 設定
          • @serializable およびその他のデコレーター
        • three
          • index
        • unity
          • Editor Sync
          • Unity用Needle Engine
      • pt
        • SUMMARY
        • Automatic Component Generation
        • Componentes Principais do Needle
        • Como Depurar
        • Implementação e Otimização
        • embedding
        • Everywhere Actions
        • Projetos de Exemplo ✨
        • Exportar Recursos, Animações, Prefabs, Materiais, Lightmaps...
        • Perguntas e Respostas (FAQ) 💡
        • Visão Geral dos Recursos
        • Esta página foi movida: continue aqui
        • getting-started
        • Frameworks, Bundlers, HTML
        • index
        • Módulos Adicionais
        • Redes
        • Estrutura do Projeto Needle Engine
        • Projetos de Exemplo
        • Exemplos de Scripting
        • Criar e usar Componentes
        • Ao Vivo
        • Ao Vivo
        • Sobre
        • Ao Vivo
        • Ao Vivo
        • Ao Vivo
        • Ao Vivo
        • Suporte e Comunidade
        • Visão Geral Técnica
        • Depoimentos
        • Testar em dispositivos locais
        • vanilla-js
        • vision
        • VR & AR (WebXR)
        • blender
          • Needle Engine para Blender
        • cloud
          • Needle Cloud
        • custom-integrations
          • index
        • getting-started
          • Introdução à Scripting para Developers Unity
          • Começar e Instalação
          • Scripting no Needle Engine
        • reference
          • needle.config.json
          • needle-engine-attributes
          • @serializable e outros decorators
        • three
          • index
        • unity
          • Sincronização do Editor
          • Needle Engine para Unity
      • vn
        • 404
        • SUMMARY
        • Automatic Component Generation
        • Các Component Cốt lõi của Needle
        • Cách gỡ lỗi
        • Triển khai và Tối ưu hóa
        • embedding
        • Hành động ở mọi nơi (Everywhere Actions)
        • Các Dự Án Ví Dụ ✨
        • Xuất Tài sản, Hoạt ảnh, Prefab, Vật liệu, Lightmap...
        • Câu hỏi thường gặp (FAQ) 💡
        • Tổng quan tính năng
        • Trang này đã được di chuyển: tiếp tục tại đây
        • getting-started
        • Frameworks, Bundlers, HTML
        • index
        • Các Module Bổ Sung
        • Kết nối mạng
        • Cấu trúc dự án Needle Engine
        • samples-and-modules
        • Ví dụ về Scripting
        • Tạo và sử dụng Component
        • Trực tiếp
        • Trực tiếp
        • Giới thiệu
        • Trực tiếp
        • Chơi thử
        • Trực tiếp
        • Demo trực tiếp
        • Hỗ trợ và Cộng đồng
        • Tổng quan kỹ thuật
        • Lời chứng thực
        • Testing on local devices
        • Sử dụng Needle Engine trực tiếp từ HTML
        • vision
        • VR & AR (WebXR)
        • blender
          • Needle Engine cho Blender
        • cloud
          • Needle Cloud
        • custom-integrations
          • index
        • getting-started
          • Giới thiệu về Scripting cho các nhà phát triển Unity
          • Getting Started & Installation
          • Scripting trong Needle Engine
        • reference
          • needle.config.json
          • Cấu hình <needle-engine>
          • @serializable và các decorator khác
        • three
          • index
        • unity
          • Editor Sync
          • Needle Engine cho Unity
      • zh
        • SUMMARY
        • 自动生成组件
        • Needle 核心组件
        • 如何调试
        • 部署与优化
        • embedding
        • Everywhere Actions
        • 示例项目 ✨
        • 导出资源、动画、预制体、材质、光照贴图...
        • 常见问题 (FAQ) 💡
        • 功能概览
        • 此页面已移动:请在此处继续
        • getting-started
        • 框架、打包器、HTML
        • index
        • 附加模块
        • 网络
        • Needle Engine 项目结构
        • 示例项目
        • Scripting Examples
        • Creating and using Components
        • 实时示例
        • 实时
        • 关于
        • 实时演示
        • 在线试玩
        • 实时演示
        • 现场演示
        • 支持与社区
        • 技术概述
        • 用户评价
        • Testing on local devices
        • 使用 Needle Engine 直接从 HTML
        • vision
        • VR & AR (WebXR)
        • blender
          • Needle Engine for Blender
        • cloud
          • Needle Cloud
        • custom-integrations
          • index
        • getting-started
          • Scripting Introduction for Unity Developers
          • 入门与安装
          • 在 Needle Engine 中编写脚本
        • reference
          • needle.config.json
          • <needle-engine> 配置
          • @serializable and other decorators
        • three
          • index
        • unity
          • 编辑器同步
          • Unity 版 Needle Engine
Powered by GitBook
On this page
Edit on GitHub
  1. documentation
  2. lang
  3. zh
  4. getting-started

在 Needle Engine 中编写脚本

Typescript、Javascript 和 C# 的区别、相似点和关键概念。

Previous入门与安装Nextreference

Last updated 26 days ago

以下指南旨在强调 C#、Javascript 和 Typescript 之间的一些主要区别。这对于刚接触 Web 生态系统的开发者最有用。

以下是一些学习如何编写 Typescript 的有用资源:

C#、Javascript 或 Typescript 之间的主要区别

CSharp 或 C# 是一种静态类型和编译型语言。这意味着在你的代码可以运行(或执行)之前,它必须被编译——转换——成 IL 或 CIL,这是一种更接近机器码的中间语言。这里需要理解的重要一点是,你的代码会被分析,并且必须通过编译器强制执行的某些检查和规则。如果你编写违反 C# 语言任何规则的代码,你将会在 Unity 中收到编译错误,并且你的应用程序甚至不会开始运行。存在编译错误时,你将无法进入 Play-Mode。

另一方面,Javascript 在运行时被解释。这意味着你可以编写无效代码并导致错误——但你不会直到你的程序运行或尝试执行包含错误的那一行时才会看到这些错误。例如,你可以编写 var points = 100; points += "hello world";,并且在浏览器中运行代码之前没有人会抱怨。

Typescript 是由 Microsoft 设计的一种语言,它编译成 javascript。 它增加了许多特性,例如类型安全。这意味着当你用 Typescript 编写代码时,你可以声明类型,因此当你尝试进行例如无效的赋值或使用非预期类型调用方法时,会在编译时收到错误。请在下面阅读更多关于 Javascript 和 Typescript 中的类型信息。

类型——或缺乏类型

(截至目前)原生 Javascript 没有任何类型的概念:你声明为 let points = 100 的变量不能保证在应用程序后面仍然是数字。这意味着在 Javascript 中,后面代码中将 points = new Vector3(100, 0, 0); 或甚至 points = null 或 points = myRandomObject——你懂的——赋值给 points 是完全有效的代码。在你编写代码时这一切都是正常的,但是当你的代码执行时,它可能会崩溃,因为你后面写了 points -= 1,而现在当你的应用程序已经在运行时,你会在浏览器中收到错误。

如上所述,创建 Typescript 是为了通过添加定义类型的语法来帮助解决这个问题。

理解这一点很重要:当你编写 Typescript 时,你基本上仍然在编写 Javascript。虽然通过例如在错误行上方添加 //@ts-ignore 或将所有类型定义为 any 可以绕过所有类型检查和安全检查,但这绝对不推荐。类型的存在是为了帮助你在错误实际发生之前找到它们。你真的不希望将网站部署到服务器后,才收到来自用户或访问者的报告,告诉你应用程序在运行时崩溃了。

虽然原生 Javascript不提供类型,你仍然可以通过使用 来为你的 javascript 变量、类和方法添加类型注释。

变量

在 C# 中,你使用类型或 var 关键字来编写变量。 例如,你可以编写 int points = 100; 或者,你可以使用 var 让编译器为你确定正确的类型:var points = 100

在 Javascript 或 Typescript 中,你有两种现代选项来声明变量。 对于你计划重新赋值的变量,使用 let,例如 let points = 100; 对于你不希望能够重新赋值的变量,使用 const,例如 const points = 100;

请注意,如果变量(例如)是自定义类型,你仍然可以为用 const 声明的变量赋值。考虑以下示例:

import { Vector3 } from "three";
// ---cut-before---
const myPosition : Vector3 = new Vector3(0, 0, 0);
myPosition.x = 100; // Assigning x is perfectly fine

上面的代码是完全正常的 Typescript 代码,因为你没有重新赋值 myPosition,只是赋值了 myPosition 的 x 成员。另一方面,以下示例将不被允许并导致运行时或 typescript 错误:

// @errors: 2588
import { Vector3 } from "three";
// ---cut-before---
const myPosition : Vector3 = new Vector3(0, 0, 0);
myPosition = new Vector3(100, 0, 0); // ⚠ ASSIGNING TO CONST IS NOT ALLOWED

使用或导入类型

在 Unity 中,你通常在代码顶部添加 using 语句来导入项目中引用的程序集中的特定命名空间,或者在某些情况下,你可能会导入命名空间中具有特定名称的特定类型。 请看以下示例:

using UnityEngine;
// importing just a specific type and giving it a name
using MonoBehaviour = UnityEngine.MonoBehaviour;

在 Typescript 中以同样的方式从包中导入特定类型:

import { Vector3 } from 'three';
import { Behaviour } from '@needle-tools/engine';

你可以通过给特定包指定名称来导入该包中的所有类型,你可能会在某些地方看到这种用法:

import * as THREE from 'three';
const myVector : THREE.Vector3 = new THREE.Vector3(1, 2, 3);

基本类型

Vector2, Vector3, Vector4... 如果你有 C# 背景,你可能熟悉类和结构体之间的区别。类是引用类型,而结构体是自定义值类型。这意味着,根据上下文,它会被分配到栈上,并且当作为参数传递给方法时,默认会创建一个副本。 考虑以下 C# 示例:

void MyCallerMethod(){
    var position = new Vector3(0,0,0);
    MyExampleVectorMethod(position);
    UnityEngine.Debug.Log("Position.x is " + position.x); // Here x will be 0
}
void MyExampleVectorMethod(Vector3 position){
    position.x = 42;
}

调用了一个方法,传入了一个名为 position 的 Vector3。在该方法内部,传入的 vector position 被修改:x 被设置为 42。但在 C# 中,传入该方法的原始 vector(参见第 2 行)没有改变,x 将仍然是 0(第 4 行)。

这对于 Javascript/Typescript 来说不是真的。这里我们没有自定义值类型,这意味着如果你在 Needle Engine 或 three.js 中遇到 Vector,你将始终拥有一个引用类型。 考虑以下 Typescript 示例:

import { Vector3 } from 'three'

function myCallerMethod() : void {
    const position = new Vector3(0,0,0);
    myExampleVectorMethod(position);
    console.log("Position.x is " + position.x); // Here x will be 42
}
function myExampleVectorMethod(position: Vector3) : void {
    position.x = 42;
}

你看到区别了吗?因为 vectors 和所有自定义对象实际上是引用类型,所以我们将修改原始的 position 变量(第 3 行),并且 x 现在是 42。

这不仅在理解方法时很重要,在处理变量时也很重要。 在 C# 中,以下代码将产生两个 Vector3 实例,改变其中一个不会影响另一个:

var myVector = new Vector3(1,1,1);
var myOtherVector = myVector;
myOtherVector.x = 42;
// will log: 1, 42
UnityEngine.Debug.Log(myVector.x + ", " + myOtherVector.x);

如果你在 Typescript 中做同样的事情,你将不会创建一个副本,而是获得对同一个 myVector 实例的引用:

import { Vector3 } from 'three'

const myVector = new Vector3(1,1,1);
const myOtherVector = myVector;
myOtherVector.x = 42;
// will log: 42, 42
console.log(myVector.x, myOtherVector.x);

Vector 运算和运算符

虽然在 C# 中可以使用运算符重载,但很遗憾 Javascript 中没有此功能。这意味着虽然你可以在 C# 中像这样乘一个 Vector3:

var myFirstVector = new Vector3(1,1,1);
var myFactor = 100f;
myFirstVector *= myFactor;
// → myFirstVector is now 100, 100, 100

你必须使用 Vector3 类型上的一个方法来达到同样的结果(只是需要多写一点样板代码)

import { Vector3 } from "three"

const myFirstVector : Vector3 = new Vector3(1, 1, 1)
const myFactor = 100;
myFirstVector.multiplyScalar(myFactor);
// → myFirstVector is now 100, 100, 100

相等检查

宽松比较 vs 严格比较

在 C# 中,当你想检查两个变量是否相同时,可以写成这样:

var playerIsNull = myPlayer == null;

在 Javascript/Typescript 中,== 和 === 之间有区别,其中 === 会更严格地检查类型:

const myPlayer: any = null;
// ---cut-before---
const playerIsNull = myPlayer === null;
const playerIsNullOrUndefined = myPlayer == null;

事件、绑定和 this

在 C# 中订阅事件时,你可以这样做:

// this is how an event is declared
event Action MyEvent;
// you subscribe by adding to (or removing from)
void OnEnable() {
    MyEvent += OnMyEvent;
}
void OnDisable() {
    MyEvent -= OnMyEvent;
}
void OnMyEvent() {}

在 Typescript 和 Javascript 中,当你向列表中添加方法时,必须“绑定 this”。这基本上意味着你创建一个方法,其中明确地将 this 设置为(通常是)你当前的类实例。有两种方法可以实现这一点。

请注意,这里我们使用了 EventList 类型,它是 Needle Engine 中用于声明事件的类型(当你将它们与我们的编辑器集成一起使用时,EventList 也会自动转换为 UnityEvent 和/或 Blender 中的事件列表)。

import { EventList, Behaviour, serializable } from "@needle-tools/engine";

export class MyComponent extends Behaviour {

    @serializable(EventList)
    myEvent!: EventList;

    onEnable() {
        this.myEvent.addEventListener(this.onMyEvent);
    }

    onDisable() {
        this.myEvent.removeEventListener(this.onMyEvent);
    }

    // Declaring the function as an arrow function to automatically bind `this`
    private onMyEvent = () => {
        console.log(this !== undefined, this)
    }
}

还有一种更详细的“经典”方法来实现同样的目的,即手动绑定 this(并将方法保存在变量中,以便稍后从事件列表中移除):

import { EventList, Behaviour, serializable } from "@needle-tools/engine";

export class MyComponent extends Behaviour {

    @serializable(EventList)
    myEvent?: EventList;

    private _onMyEventFn?: Function;

    onEnable() {
        // bind this
        this._onMyEventFn = this.onMyEvent.bind(this);
        // add the bound method to the event
        this.myEvent?.addEventListener(this._onMyEventFn);
    }

    onDisable() {
        this.myEvent?.removeEventListener(this._onMyEventFn);
    }

    // Declaring the function as an arrow function to automatically bind `this`
    private onMyEvent = () => { }
}

接下来做什么?


页面由人工智能自动翻译

注意 var 你可能也会在 javascript 中遇到 var 关键字,但不推荐使用它,并且它的现代替代方案是 let。了解更多关于 。

你注意到第二个变量 playerIsNullOrUndefined 使用了 ==,它进行宽松相等检查,在这种情况下,null 和 undefined 都将在此处导致 true。你可以阅读更多相关信息。

实现此目的的简短且推荐的语法是使用。

Typescript Tutorial
Learn Typescript
Typescript Documentation
JSDoc
var vs let
在这里
箭头函数
Needle Engine Scripting