简体   繁体   English

如何在 C#/Unity 中不使用 Find() 获取对 GameObject 的引用?

[英]How to get reference to GameObject without using Find() in C#/Unity?

I am currently taking an intro to games programming class and in the lecture notes it mentions that instead of using something like:我目前正在介绍游戏编程 class 并在讲义中提到,而不是使用类似的东西:

GameObject obj = GameObject.Find("name");

inside functions, you can "add object as Public member of type GameObject and connect it in the inspector" without actually explaining how to do it.在函数内部,您可以“将 object 添加为 GameObject 类型的公共成员并在检查器中连接它”,而无需实际解释如何操作。

I tried to lookup how to do this but was unable to find how to properly do so, would appreciate any help.我试图查找如何做到这一点,但无法找到如何正确地做到这一点,将不胜感激。

Here is how you could do it.这是你可以做到的。 Lets say you want obj2 in obj1假设你想要obj1中的obj2

First go in the script of obj1 and declare a public variable public GameObject obj2;首先在obj1的脚本中go并声明一个public变量public GameObject obj2;

Then go in to the inspector of the obj1 , on script component you will find a field Obj2 .然后 go 进入obj1的检查器,在脚本组件上你会找到一个字段Obj2 Now just drag and drop the obj2 from hierarchy in that field or click a circular button next to field and select the object from the list.现在只需从该字段的层次结构中拖放obj2或单击字段旁边的圆形按钮,然后从列表中单击 select 和 object。

If you use the public access-modifier, or for fields with the private (default), internal or protected access-modifier, if you annotate with [SerializeField] , they will show up in the inspector, if they are serializable and of a supported type.如果您使用public访问修饰符,或者对于具有private (默认)、 internalprotected访问修饰符的字段,如果您使用[SerializeField]进行注释,它们将显示在检查器中,如果它们是可序列化的并且受支持类型。

//This is shown in the inspector
public string _publicField = "public field";

//This is not shown in the inspector, unless you are in debug mode.
private string _privateField = "private field";

//This is shown in the inspector
[SerializeField]
private string _annotatedPrivateField = "annotated private field";

As for what the inspector is:至于检查员是什么:

The Inspector window (sometimes referred to as “the Inspector”) displays detailed information about the currently selected GameObject, including all attached components and their properties, and allows you to modify the functionality of GameObjects in your Scene.检查器 window(有时称为“检查器”)显示有关当前选定游戏对象的详细信息,包括所有附加组件及其属性,并允许您修改场景中游戏对象的功能。

在此处输入图像描述

From the official documentation.来自官方文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM