首页 > 解决方案 > 如何:获取游戏对象的实例

问题描述

想要获得这个游戏对象的一个​​实例,这样我就可以成功地使用 .enabled 将它隐藏在场景中。

PlayPortalLoginButton loginButton = gameObject.GetComponent<PlayPortalLoginButton>();

对 C# 相当陌生,我相信我已经接近实现上述目标的目标。什么需求改变了?想了解如何正确地做到这一点。

标签: c#unity3dgameobject

解决方案


这是您可以GameObject在场景中找到组件的一种方法,其中“PortalLoginButton”是GameObject在编辑器中看到的名称:

var loginButton = GameObject.Find("PortalLoginButton");
loginButton.enabled = false;

但是,GameObject.Find("...")搜索GameObject场景中每个的名称,这通常不是引用 a 的最佳方法,GameObject因为它不是很有效。所以请确保不要在函数中使用GameObject.Find("...")或类似的函数调用,Update()因为它会执行每一帧并减慢您的游戏速度。如果在GameObject游戏运行时未实例化 ,通常最好对您在脚本中使用的任何GameObject或进行全局引用,然后将您要查找Component的 拖放到编辑器中的字段中。或者,您可以在or函数中使用来存储对GameObjectComponentGameObject.Find("...")Start()Awake()GameObject你正在寻找的,所以搜索只在你的游戏开始时发生一次。

这是一个如何将引用存储在全局字段中的示例(它将显示在编辑器中,您可以将其拖放GameObject到其中)。评论中解释了使用公共字段与私有字段之间的区别(您可以决定使用公共字段还是私有字段):

// By default, private fields are not viewable in the editor,
// but the [SerializeField] attribute, placed before
// the field declaration, allows them to be visible.
[SerializeField]
private GameObject loginButtonPrivateReference;
// If you need to access loginButton from another script, 
// you can make it a public field.
// Public fields are viewable in the editor by default.
public GameObject loginButtonPublicReference;

以下是如何在Awake()函数中使用 GameObject.Find("...") 的示例:

private GameObject loginButton;

private void Awake() {
    loginButton = GameObject.Find("PortalLoginButton");
}

如果您需要按类型或标签名称在场景中搜索GameObjects,请参阅此处GameObject的文档以获取更多信息。按类型搜索效率较低,而按标签搜索比按名称搜索更有效,因为类型搜索会检查每个 上的每个组件,而标签搜索仅搜索有组织的子集。GameObjectGameObject


推荐阅读