c# - GetComponentInParent () 不改变父组件
问题描述
当玩家点击孩子时,我希望孩子改变父母的彩色图像组件。这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class DragOption : MonoBehaviour, IPointerClickHandler
{
public void OnPointerClick(PointerEventData eventData)
{
GetComponentInParent<Image>().color = new Color32(255, 235, 0, 255);
}
}
但是,不是父母被改变为新的颜色,而是孩子被改变了。这些有解决办法吗?
解决方案
GetComponentInParent
包括对调用对象本身的组件搜索。
返回GameObject或其任何父级中 Type 类型的组件。
因此,如果您的“孩子”Image
本身也有一个组件(如果我理解正确的话就是这种情况),它将返回那个组件。
为了确保它至少启动上面的一位父母,您宁愿这样做
transform.parent.GetComponentInParent<Image>().color = new Color32(255, 235, 0, 255);
或者如果您确定直接父母是您想要的直接父母,您可以直接做
transform.parent.GetComponent<Image>().color = new Color32(255, 235, 0, 255);
推荐阅读
- apache-kafka - Pepper-box 的 JMeter Kafka 测试。Jmeter错误:PlaintTextLoadGenerator:请确保...参数正确传递
- react-native - 在 React Native View 元素中添加诸如属性之类的样式是否正确?
- python - 对 BigQuery 表中的敏感数据进行匿名处理
- java - 如何使用 Snakeyaml 读取/写入 java.time.Duration
- javascript - 如何从反应引导表中的 onSelectAll 复选框设置反应使用状态数组
- python - 为每个新值替换值和重复行
- last.fm - Last.fm scrobbling API 不返回更正
- javascript - JS 打开打印对话框页面打印一个pdf文件
- arrays - 当我将数组值用作 bash 脚本中位置参数的输入时,我丢失了数组值
- c# - Pdfsharp - 悬停在矩形上时无法弹出注释