c# - 如何:获取游戏对象的实例
问题描述
想要获得这个游戏对象的一个实例,这样我就可以成功地使用 .enabled 将它隐藏在场景中。
PlayPortalLoginButton loginButton = gameObject.GetComponent<PlayPortalLoginButton>();
对 C# 相当陌生,我相信我已经接近实现上述目标的目标。什么需求改变了?想了解如何正确地做到这一点。
解决方案
这是您可以GameObject
在场景中找到组件的一种方法,其中“PortalLoginButton”是GameObject
在编辑器中看到的名称:
var loginButton = GameObject.Find("PortalLoginButton");
loginButton.enabled = false;
但是,GameObject.Find("...")
搜索GameObject
场景中每个的名称,这通常不是引用 a 的最佳方法,GameObject
因为它不是很有效。所以请确保不要在函数中使用GameObject.Find("...")
或类似的函数调用,Update()
因为它会执行每一帧并减慢您的游戏速度。如果在GameObject
游戏运行时未实例化 ,通常最好对您在脚本中使用的任何GameObject
或进行全局引用,然后将您要查找Component
的 拖放到编辑器中的字段中。或者,您可以在or函数中使用来存储对GameObject
Component
GameObject.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
的文档以获取更多信息。按类型搜索效率较低,而按标签搜索比按名称搜索更有效,因为类型搜索会检查每个 上的每个组件,而标签搜索仅搜索有组织的子集。GameObject
GameObject
推荐阅读
- android - 无法在 Google Play 开发者控制台中选择“世界其他地区”选项
- scala - 如何扩展一个扩展 App 的类
- java - webview 不会随着 javafx 中的屏幕最大化
- properties - Delphi 7 - 更改字体子属性不会更新组件
- database - Should I have index with all Where-clause fields?
- time-complexity - 图算法的运行时间
- java - 为什么只有在我在 OpenShift 上部署时,Google Sheets API 才会给我一个 invalid_scope 错误?
- c# - Json.net JsonPath 过滤器与联合
- sql - SQL Server:如何检查组列表中的每个组是否存在记录?
- c# - DateTime 字符串格式错误