首页 > 解决方案 > 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);
   }
}

但是,不是父母被改变为新的颜色,而是孩子被改变了。这些有解决办法吗?

标签: c#unity3d

解决方案


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);

推荐阅读