Maison base de données tutoriel 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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion

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>
Copier après la connexion
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Comment désinstaller complètement Xbox Game Bar sous Win11 ? Partager comment désinstaller Xbox Game Bar Comment désinstaller complètement Xbox Game Bar sous Win11 ? Partager comment désinstaller Xbox Game Bar Feb 10, 2024 am 09:21 AM

Comment désinstaller complètement Win11XboxGameBar ? Xbox GameBar est la plate-forme de jeu fournie avec le système. Elle fournit des outils pour l'enregistrement de jeux, des captures d'écran et des fonctions sociales. Cependant, elle prend beaucoup de mémoire et n'est pas facile à désinstaller, mais certains amis souhaitent la désinstaller. pas question. Comment le désinstaller complètement, laissez-moi vous le présenter ci-dessous. Méthode 1. Utiliser le terminal Windows 1. Appuyez sur la combinaison de touches [Win+X] ou [clic droit] cliquez sur [Menu Démarrer de Windows] dans la barre des tâches et sélectionnez [Administrateur de terminal] dans l'élément de menu qui s'ouvre. 2. Fenêtre Contrôle de compte d'utilisateur, souhaitez-vous autoriser cette application à apporter des modifications à votre appareil ? Cliquez sur [Oui]. 3. Exécutez la commande suivante : Get-AppxP

Black Myth : Wukong écrase la concurrence avec 2,2 millions de joueurs Steam quelques heures seulement après son lancement Black Myth : Wukong écrase la concurrence avec 2,2 millions de joueurs Steam quelques heures seulement après son lancement Aug 21, 2024 am 10:25 AM

Le battage médiatique autour de Black Myth : Wukong s'est fait sentir à l'échelle mondiale alors que le jeu avançait lentement vers sa date de lancement, et il n'a pas déçu lors de son lancement le 20 août, après avoir reçu un accueil très chaleureux de la part de la communauté des joueurs dans son ensemble. Après avoir été seul

La taille de téléchargement de Sonic X Shadow Generations révélée pour Nintendo Switch via la liste officielle La taille de téléchargement de Sonic X Shadow Generations révélée pour Nintendo Switch via la liste officielle Jul 30, 2024 am 09:42 AM

Fort du succès de son prédécesseur, Sonic Generations (39 $ sur Amazon), Sega devrait sortir Sonic X Shadow Generations le 25 octobre 2024. Titre très attendu depuis un moment déjà, Sega étend le jeu original. pour

Sleeping Dogs: Definitive Edition pour PC tombe à un plus bas historique de 2,99 $ sur GOG Sleeping Dogs: Definitive Edition pour PC tombe à un plus bas historique de 2,99 $ sur GOG Aug 31, 2024 am 09:52 AM

Sleeping Dogs: Definitive Edition est actuellement disponible à un prix fortement réduit de seulement 2,99 $ sur GOG, offrant une réduction massive de 85 % par rapport à son prix initial de 19,99 $. Pour profiter de cette offre, visitez simplement la page du jeu sur GOG, ajoutez

Le jeu de tir de Square Enix, Foamstars, deviendra gratuit après une hémorragie de joueurs après sa sortie en février Le jeu de tir de Square Enix, Foamstars, deviendra gratuit après une hémorragie de joueurs après sa sortie en février Aug 28, 2024 pm 01:09 PM

Foamstars de Square Enix a initialement reçu un très bon accueil, battant le succès Helldivers 2 le jour de son lancement – ​​probablement en raison de son lancement dans le cadre du programme de jeux mensuel PS Plus. Cependant, le nombre de joueurs a rapidement chuté.

Mise à jour de la version préliminaire de Win11 Build 226×1.2271, tous les utilisateurs du canal Windows Insider sont invités à découvrir la nouvelle version du Microsoft Store Mise à jour de la version préliminaire de Win11 Build 226×1.2271, tous les utilisateurs du canal Windows Insider sont invités à découvrir la nouvelle version du Microsoft Store Sep 17, 2023 am 09:29 AM

Microsoft a publié aujourd'hui la mise à jour préliminaire Win11Build226 × 1.2271 pour le canal bêta et a invité tous les utilisateurs du canal WindowsInsider à découvrir la nouvelle version du Microsoft Store. La dernière version du Microsoft Store est 22308.1401.x.x Nouvelle page GamePass : Microsoft a annoncé avoir introduit une nouvelle page dédiée qui permet aux joueurs d'explorer et de s'abonner à PC GamePass ou GamePass Ultimate. Les utilisateurs peuvent découvrir les nombreux avantages du GamePass, notamment les jeux exclusifs, les réductions, les avantages gratuits, EAPlay, etc. Microsoft espère que les utilisateurs ne passeront pas à

Microsoft offre gratuitement un jeu de construction rétro, mais seulement pour une durée limitée. Microsoft offre gratuitement un jeu de construction rétro, mais seulement pour une durée limitée. Sep 07, 2024 pm 09:30 PM

Hero of the Kindgom II n'est pas le seul jeu de Lonely Troops actuellement proposé gratuitement sur le Microsoft Store. Jusqu'au 9 septembre, les joueurs peuvent également obtenir gratuitement Townpolis, un jeu de construction de 2008 qui coûte régulièrement 5 $. Townpolis met le jeu

Microsoft offre un jeu d'aventure RPG très populaire Microsoft offre un jeu d'aventure RPG très populaire Sep 07, 2024 am 06:39 AM

Hero of the Kingdom II est un jeu d'aventure avec des éléments RPG dans lequel les joueurs incarnent un simple agriculteur qui vit avec sa sœur dans un village tranquille. Mais l'idylle est bientôt perturbée par des raids de pirates, après quoi ils entreprennent de sauver le roi.

See all articles