search
HomeDatabaseMysql TutorialOverview: Accessing Other Game Objects 访问其他游戏物体

Most advanced game code does not only manipulate a single object. The Unity scripting interface has various ways to find and access other game objects and components there-in. In the following we assume there is a script named OtherScript.

Most advanced game code does not only manipulate a single object. The Unity scripting interface has various ways to find and access other game objects and components there-in. In the following we assume there is a script named OtherScript.js attached to game objects in the scene.

多数高级的游戏代码并不仅仅控制单独的游戏对象. Unity脚本有很多方法去查找和访问他们的游戏对象和组件.下面我们假设一个脚本OtherScript.js附于场景中的一个游戏对象上.

  • C#
  • JavaScript

<code>function Update () {
    otherScript = GetComponent(OtherScript);
    otherScript.DoSomething();
}</code>

1. Through inspector assignable references. 
通过检视面板指定参数.

You can assign variables to any object type through the inspector:

你能通过检视面板为一些对象类型设置变量值:

  • C#
  • JavaScript

<code><span>// Translate the object dragged on the target slot
// 将要转换的对象拖拽到target位置</span>

var target : Transform;
function Update () {
    target.Translate(0, 1, 0);
}</code>

You can also expose references to other objects to the inspector. Below you can drag a game object that contains the OtherScript on the target slot in the inspector.

你也可以把参数显示在检视面板.随后你可以拖拽游戏对象OtherScript到检视面板中的target位置.

  • C#
  • JavaScript

<code>using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    public OtherScript target;
    void Update() {
        target.foo = 2;
        target.DoSomething("Hello");
    }
}</code>

2. Located through the object hierarchy. 
确定对象的层次关系

You can find child and parent objects to an existing object through the Transform component of a game object:

你能通过游戏对象的 Transform 组件去找到它的子对象或父对象:

  • C#
  • JavaScript

<code><span>// Find the child "Hand" of the game object
//获得子游戏对象"Hand" 
// we attached the script to
// 我们现在的脚本为</span>

transform.Find("Hand").Translate(0, 1, 0);</code>

Once you have found the transform in the hierarchy, you can use GetComponent to get to other scripts.

一旦你在层次视图找到transform,你便能用 GetComponent 获取其他脚本.

  • C#
  • JavaScript

<code><span>// Find the child named "Hand".
// On the OtherScript attached to it, set foo to 2.
// 找到子对象 "Hand".
// 获取OtherScript,设置foo为2</span>.
transform.Find("Hand").GetComponent(OtherScript).foo = 2;

<span>// Find the child named "Hand".
// Call DoSomething on the OtherScript attached to it.
// 获得子对象"Hand".
// 调用附属于它的 OtherScript的DoSomething.</span>
transform.Find("Hand").GetComponent(OtherScript).DoSomething("Hello");

<span>// Find the child named "Hand".
// Then apply a force to the rigidbody attached to the hand.
//获得子对象"Hand".
// 加一个力到刚体上</span>
transform.Find("Hand").rigidbody.AddForce(0, 10, 0);</code>

You can loop over all children: 你能循环到所有的子对象:

  • C#
  • JavaScript

<code><span>// Moves all transform children 10 units upwards!
//向上移动所有的子对象1个单位!</span>

for (var child : Transform in transform) {
    child.Translate(0, 10, 0);
}</code>

See the documentation for the Transform class for further information.

查看文档 Transform 类可以获得更多信息.

3. Located by name or Tag. 

You can search for game objects with certain tags using GameObject.FindWithTag and GameObject.FindGameObjectsWithTag . Use GameObject.Find to find a game object by name.

GameObject.FindWithTag 和 GameObject.FindGameObjectsWithTag .使用 GameObject.Find 通过名字获得游戏对象.

  • C#
  • JavaScript

<code>function Start () {
    <span>// By name 通过名字</span>
    var go = GameObject.Find("SomeGuy");
    go.transform.Translate(0, 1, 0);

    
    var player = GameObject.FindWithTag("Player");
    player.transform.Translate(0, 1, 0);

}</code>

You can use GetComponent on the result to get to any script or component on the found game object

你可以用GetComponent获得指定游戏对象上的任意脚本或组件.

  • C#
  • JavaScript

<code>function Start () {
    <span>// By name 通过名字</span>
    var go = GameObject.Find("SomeGuy");
    go.GetComponent(OtherScript).DoSomething();

    
    var player = GameObject.FindWithTag("Player");
    player.GetComponent(OtherScript).DoSomething();
}</code>

Some special objects like the main camera have shorts cuts using Camera.main .

一些特殊对象,比如主摄像机,用快捷方式 Camera.main .

4. Passed as parameters. 传递参数

Some event messages contain detailed information on the event. For instance, trigger events pass the Collider component of the colliding object to the handler function.

一些事件包含详细的消息信息.例如,触发事件传递碰撞对象的 Collider 组件到处理函数.

OnTriggerStay gives us a reference to a collider. From the collider we can get to its attached rigidbody.

OnTriggerStay给我们一个碰撞体参数.通过这个碰撞体我们能得到它的刚体.

  • C#
  • JavaScript

<code>function OnTriggerStay( other : Collider ) {
    <span>// If the other collider also has a rigidbody
    // apply a force to it!
    // 如果碰撞体有一个刚体
    // 给他一个力!</span>

    if (other.rigidbody)
    other.rigidbody.AddForce(0, 2, 0);
}</code>

Or we can get to any component attached to the same game object as the collider.

或者我们可以通过collider得到这个物体的任何组件.

  • C#
  • JavaScript

<code>function OnTriggerStay( other : Collider ) {
    <span>// If the other collider has a OtherScript attached
    // call DoSomething on it.
    // Most of the time colliders won't have this script attached,
    // so we need to check first to avoid null reference exceptions.
    // 如果其他的碰撞体附加了OtherScript 
    // 调用他的DoSomething.
    // 一般碰撞体没有附脚本,
    // 所以我们需要首先检查是否为null.</span>

    if (other.GetComponent(OtherScript))
    other.GetComponent(OtherScript).DoSomething();
}</code>

Note that by suffixing the other variable in the above example, you can access any component inside the colliding object.

注意, 在上面的例子中使用后缀的方式访问其他变量.同样,你能访问到碰撞对象包含的任意组件。

5. All scripts of one Type 某个类型的脚本

Find any object of one class or script name using Object.FindObjectsOfType or find the first object of one type using Object.FindObjectOfType .

找到某个类型的对象或脚本可以用 Object.FindObjectsOfType 或获得某个类型的第一个对象使用 Object.FindObjectOfType .

  • C#
  • JavaScript

<code>using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Start() {
        OtherScript other = FindObjectOfType(typeof(OtherScript));
        other.DoSomething();
    }
}</code>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the different storage engines available in MySQL?What are the different storage engines available in MySQL?Apr 26, 2025 am 12:27 AM

MySQLoffersvariousstorageengines,eachsuitedfordifferentusecases:1)InnoDBisidealforapplicationsneedingACIDcomplianceandhighconcurrency,supportingtransactionsandforeignkeys.2)MyISAMisbestforread-heavyworkloads,lackingtransactionsupport.3)Memoryengineis

What are some common security vulnerabilities in MySQL?What are some common security vulnerabilities in MySQL?Apr 26, 2025 am 12:27 AM

Common security vulnerabilities in MySQL include SQL injection, weak passwords, improper permission configuration, and unupdated software. 1. SQL injection can be prevented by using preprocessing statements. 2. Weak passwords can be avoided by forcibly using strong password strategies. 3. Improper permission configuration can be resolved through regular review and adjustment of user permissions. 4. Unupdated software can be patched by regularly checking and updating the MySQL version.

How can you identify slow queries in MySQL?How can you identify slow queries in MySQL?Apr 26, 2025 am 12:15 AM

Identifying slow queries in MySQL can be achieved by enabling slow query logs and setting thresholds. 1. Enable slow query logs and set thresholds. 2. View and analyze slow query log files, and use tools such as mysqldumpslow or pt-query-digest for in-depth analysis. 3. Optimizing slow queries can be achieved through index optimization, query rewriting and avoiding the use of SELECT*.

How can you monitor MySQL server health and performance?How can you monitor MySQL server health and performance?Apr 26, 2025 am 12:15 AM

To monitor the health and performance of MySQL servers, you should pay attention to system health, performance metrics and query execution. 1) Monitor system health: Use top, htop or SHOWGLOBALSTATUS commands to view CPU, memory, disk I/O and network activities. 2) Track performance indicators: monitor key indicators such as query number per second, average query time and cache hit rate. 3) Ensure query execution optimization: Enable slow query logs, record and optimize queries whose execution time exceeds the set threshold.

Compare and contrast MySQL and MariaDB.Compare and contrast MySQL and MariaDB.Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

How does MySQL's licensing compare to other database systems?How does MySQL's licensing compare to other database systems?Apr 25, 2025 am 12:26 AM

MySQL uses a GPL license. 1) The GPL license allows the free use, modification and distribution of MySQL, but the modified distribution must comply with GPL. 2) Commercial licenses can avoid public modifications and are suitable for commercial applications that require confidentiality.

When would you choose InnoDB over MyISAM, and vice versa?When would you choose InnoDB over MyISAM, and vice versa?Apr 25, 2025 am 12:22 AM

The situations when choosing InnoDB instead of MyISAM include: 1) transaction support, 2) high concurrency environment, 3) high data consistency; conversely, the situation when choosing MyISAM includes: 1) mainly read operations, 2) no transaction support is required. InnoDB is suitable for applications that require high data consistency and transaction processing, such as e-commerce platforms, while MyISAM is suitable for read-intensive and transaction-free applications such as blog systems.

Explain the purpose of foreign keys in MySQL.Explain the purpose of foreign keys in MySQL.Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor