unity3d - 从另一个脚本访问组件
问题描述
我正在使用统一,我试图访问Outline
在我的父对象上调用的脚本。我需要Outline
从另一个名为Destroyable
. 我知道那里有很多教程和其他问题,但似乎总是找不到。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destroyable : MonoBehaviour
{
Outline myScript;
private void OnMouseDown()
{
Destroy(gameObject);
}
// Start is called before the first frame update
private void Start()
{
myScript = gameObject.GetComponent<Outline>();
}
// Update is called once per frame
void Update()
{
}
}
解决方案
如果它们在同一个物体上
myScript = GetComponent<Outline>();
应该已经给你你想要的参考。
否则,如果您说它在父对象上,则应改为使用
myScript = transform.parent.GetComponent<Outline>();
或GetComponentInParent(仅当组件已启用且游戏对象在开始时处于活动状态)
myScript = GetComponentInParent<Outline>();
更好的(如果可能的话)是你把它变成一个[SerializeField]
[SerializeField] private Outline myScript;
并通过 Inspector 直接引用它,而不是您根本不必使用它GetComponent
。在字段中拖放相应GameObject
的,它会自动获取相应的组件引用。
为了启用或禁用它,只需设置MonoBehaviour.enabled
myScript.enabled = true; // or false
推荐阅读
- c++ - 将两个 uint16_t 数字相乘得到一个 int
- robotframework - 在 Robot Framework/Selenium 中使用 BrowserMobProxy 将 URL 列入黑名单?
- python - 笔记本和终端启动错误的python版本
- python - suds with python 2.7 如何防止 ssl.SSLError: ('读取操作超时',)
- javascript - 在角度 6 中导入没有路径的模块
- php - php执行powershell
- continuous-integration - VSTFS 构建错误 - SSL 证书问题:无法获取本地颁发者证书
- javascript - PDF 打印中的页码,仅使用 HTML、CSS 和 JavaScript?
- angularjs - 使用 AngularJS 和 $httprequest 在另一个方法中捕获方法的返回
- datagrip - 如何使 DataGrip 显示更多输出选项卡