데이터 베이스 MySQL 튜토리얼 Overview: Accessing Other Game Objects 访问其他游戏物体

Overview: Accessing Other Game Objects 访问其他游戏物体

Jun 07, 2016 pm 03:50 PM
game

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>
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Win11에서 Xbox Game Bar를 완전히 제거하는 방법은 무엇입니까? Xbox Game Bar를 제거하는 방법 공유 Win11에서 Xbox Game Bar를 완전히 제거하는 방법은 무엇입니까? Xbox Game Bar를 제거하는 방법 공유 Feb 10, 2024 am 09:21 AM

Win11XboxGameBar를 완전히 제거하는 방법은 무엇입니까? Xbox GameBar는 시스템과 함께 제공되는 게임 플랫폼입니다. 게임 녹화, 스크린샷 및 소셜 기능을 위한 도구를 제공하지만 메모리를 많이 차지하고 제거하기가 쉽지 않습니다. 안돼요. 완전히 제거하는 방법은 아래에서 소개해드리겠습니다. 방법 1. Windows 터미널 사용 1. [Win+X] 키 조합을 누르거나 [마우스 오른쪽 버튼 클릭] 작업 표시줄의 [Windows 시작 메뉴]를 클릭하고 나타나는 메뉴 항목에서 [터미널 관리자]를 선택합니다. 2. 사용자 계정 컨트롤 창에서 이 앱이 장치를 변경할 수 있도록 허용하시겠습니까? [예]를 클릭하세요. 3. 다음 명령을 실행합니다: Get-AppxP

검은 신화: 오공은 출시 후 불과 몇 시간 만에 220만 명의 Steam 플레이어로 경쟁을 압도했습니다. 검은 신화: 오공은 출시 후 불과 몇 시간 만에 220만 명의 Steam 플레이어로 경쟁을 압도했습니다. Aug 21, 2024 am 10:25 AM

Black Myth: Wukong에 대한 과대 광고는 게임이 출시일을 향해 천천히 나아가면서 전 세계적으로 느껴졌으며, 8월 20일 출시되었을 때 실망하지 않았으며 전체 게임 커뮤니티로부터 매우 따뜻한 환영을 받았습니다. 온라인 상태가 된 후

공식 목록을 통해 Nintendo Switch용 Sonic X Shadow Generations 다운로드 크기 공개 공식 목록을 통해 Nintendo Switch용 Sonic X Shadow Generations 다운로드 크기 공개 Jul 30, 2024 am 09:42 AM

전작인 Sonic Generations(Amazon에서 39달러)의 성공을 바탕으로 Sega는 2024년 10월 25일 Sonic X Shadow Generations를 출시할 예정입니다. 한동안 기다려온 타이틀인 Sega는 원작 게임의 확장을 이루고 있습니다. ~을 위한

Sleeping Dogs: PC용 Definitive Edition이 GOG에서 사상 최저 가격인 2.99달러로 떨어졌습니다. Sleeping Dogs: PC용 Definitive Edition이 GOG에서 사상 최저 가격인 2.99달러로 떨어졌습니다. Aug 31, 2024 am 09:52 AM

Sleeping Dogs: Definitive Edition은 현재 GOG에서 대폭 할인된 가격인 $2.99에 구매 가능하며, 원래 가격인 $19.99에서 85% 할인된 가격으로 제공됩니다. 이 거래를 이용하려면 GOG의 게임 페이지를 방문하여 추가하세요.

Square Enix 슈팅 게임 Foamstars, 2월 출시 후 플레이어 출혈 후 무료 플레이 가능 Square Enix 슈팅 게임 Foamstars, 2월 출시 후 플레이어 출혈 후 무료 플레이 가능 Aug 28, 2024 pm 01:09 PM

Square Enix의 Foamstars는 처음에 매우 강력한 반응을 얻었으며 출시일에 대히트를 기록한 Helldivers 2를 제치고 출시된 것으로 알려졌습니다. 아마도 PS Plus 월간 게임 프로그램의 일부로 출시되었기 때문일 것입니다. 그러나 해당 플레이어 수는 곧 감소했습니다.

Microsoft는 제한된 기간 동안만 무료로 복고풍 건설 게임을 제공합니다. Microsoft는 제한된 기간 동안만 무료로 복고풍 건설 게임을 제공합니다. Sep 07, 2024 pm 09:30 PM

Hero of the Kindgom II는 현재 Microsoft Store에서 무료로 제공되는 Lonely Troops의 유일한 게임이 아닙니다. 9월 9일까지 게이머들은 타운폴리스(Townpolis)를 무료로 얻을 수 있습니다. 이 게임은 2008년에 출시되었으며 정기적으로 5달러에 판매되는 건설 게임입니다. 타운폴리스는 플레이를 넣습니다

Win11 Build 226×1.2271 미리 보기 버전 업데이트, 모든 Windows Insider 채널 사용자는 Microsoft Store의 새 버전을 경험하도록 초대됩니다. Win11 Build 226×1.2271 미리 보기 버전 업데이트, 모든 Windows Insider 채널 사용자는 Microsoft Store의 새 버전을 경험하도록 초대됩니다. Sep 17, 2023 am 09:29 AM

Microsoft는 오늘 베타 채널에 대한 Win11Build226×1.2271 미리 보기 업데이트를 출시하고 모든 WindowsInsider 채널 사용자에게 Microsoft Store의 새 버전을 경험하도록 초대했습니다. Microsoft Store의 최신 버전은 22308.1401.x.x입니다. 새로운 GamePass 페이지: Microsoft는 플레이어가 PC GamePass 또는 GamePass Ultimate를 탐색하고 구독할 수 있는 새로운 전용 페이지를 도입했다고 밝혔습니다. 사용자는 독점 게임, 할인, 무료 혜택, EAPlay 등 GamePass의 다양한 혜택에 대해 알아볼 수 있습니다. Microsoft는 사용자가

Microsoft, 매우 인기 있는 RPG 어드벤처 게임 출시 Microsoft, 매우 인기 있는 RPG 어드벤처 게임 출시 Sep 07, 2024 am 06:39 AM

Hero of the Kingdom II는 플레이어가 조용한 마을에서 여동생과 함께 사는 단순한 농부의 역할을 맡는 RPG 요소가 포함된 어드벤처 게임입니다. 그러나 해적의 습격으로 짧은 서사시가 혼란에 빠지고 그들은 왕을 구하기 위해 나섰습니다.

See all articles