---
title: 脚本导入
slug: world-sdk-guide-ch/5VHULePERswi6onMrn7fR
docTags: 
createdAt: 2024-09-02T08:34:13.135Z
---

除了附加到 GameObject，ZEPETOScript 还可以被其他脚本直接使用。

您可以像使用库或模块一样简单地导入和使用 ZEPETOScript。在 TypeScript 语法中，您需要使用相对路径来指向 ZEPETOScript 文件。

考虑以下情况，如果您想将 ExtraComponent 导入到 ScriptImport 中，您需要使用以下语法。

以下示例是在 ScriptImport.ts 中声明以调用位于 lib 文件夹中的 ExtraComponent.TS。

:::CodeblockTabs
TypeScript

```typescript
import ExtraComponent from './lib/ExtraComponent';
```
:::



::Image[]{src="https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-HSSAVN3PdE6c87FlgO8hV-20240904-102417.png" size="42" width="200" height="80" position="center" showCaption="false"}

:::hint{type="success"}
## 👍 提示

- 在导入另一个 TS 文件时，正确指定路径非常重要。
- 请熟悉相对路径表示法。
- `./` 表示当前目录。
- `../` 表示父目录，即当前目录上一级的目录。
:::



您可以通过直接引用导入脚本中声明的导出函数和变量来访问它们，如示例所示。

```typescript
this.gameObject.AddComponent<ExtraComponent>();
const extraComponent = this.gameObject.GetComponent<ExtraComponent>();

// 通过方法调用获取值
const count = extraComponent.GetCount();
// 通过方法调用设置值
extraComponent.SetCount(0);
// 获取公共属性
const resultString = extraComponent.stringProperty;
```



以下是显示导入的 TypeScript 的示例代码。

```typescript
import { ZepetoScriptBehaviour } from 'ZEPETO.Script';
import { Text } from 'UnityEngine.UI';
// 从路径导入自定义脚本
import ExtraComponent from './lib/ExtraComponent';

export default class ScriptImport extends ZepetoScriptBehaviour {

    public resultUI: Text;
    private extComponent: ExtraComponent;

    Start() {
        // 添加脚本组件
        this.gameObject.AddComponent<ExtraComponent>();
        this.extComponent = this.gameObject.GetComponent<ExtraComponent>();
    }

    Update() {
        // 通过方法调用获取值
        const count = this.extComponent.GetCount();

        if (count > 10) {
            // 通过方法调用设置值
            this.extComponent.SetCount(0);
        }

        // 获取公共属性
        const resultString = this.extComponent.stringProperty;

        // 打印结果
        console.log(`result : ${resultString}`);
        this.resultUI.text = resultString;
    }
}
```



ExtraComponents 的示例代码。

```typescript
import { ZepetoScriptBehaviour } from 'ZEPETO.Script';

export default class ExtraComponent extends ZepetoScriptBehaviour {
    
    public stringProperty: string;
    private message: string;
    private count: int;

    Start() {
        this.message = "嗨，Zepeto！";
        this.count = 0;
    }
     
    Update() {
        this.stringProperty = `${this.message} : ${this.count++}`;
    }
     
    GetCount() {
        return this.count;
    }
     
    SetCount(newCount: int) {
        this.count = newCount;
    }

}
```



请查看下面的测试代码输出屏幕。

![](https://api.archbee.com/api/optimize/fCt3n1oCa8rgNJ8fw9I2N-fJN9RjCNK8pElFEigtqJ6-20240904-102417.png "2-10-1 (1).png")

