Unity如何使用GameObject获取GetCompoent <Outline>()和GetCompoent <Shadow>()

时间:2019-11-22 07:26:13

标签: c# unity3d

 public class ABCD : MonoBehaviour
        {
            [SerializeField]
            Outline outline;
            [SerializeField]
            Shadow shadow;

            private void Start()
            {
                outline = GetComponent<Outline>();
                shadow = GetComponent<Shadow>();
            }
        }

enter image description here

我们知道Outline是这样的实现Shadow

enter image description here

所以当我打电话

shadow = GetCompoent<Shadow>();

因为Ouline也是Shadow,所以有可能找到大纲组件。

我的问题是如何获得合适的Compoent?

而且我不能放弃该组件以保持引用。 因为我的代码完全像这样

//this not a monobehavior
class MyText
{
    Shadow shadow;
    Outline outline;
    public MyText(Transfrom transfrom)
    {
        outline = transfrom.GetComponent<Outline>();
        shadow = transfrom.GetComponent<Shadow>();
    }
}

如果我创建Compoent来保留引用,则会花费更多的费用。


使用GetCompoents可以解决这个问题吗,有人有更好的解决方案吗?

 foreach (Shadow s in GetComponents<Shadow>())
            {
                if (s is Outline)
                {
                    outline = s as Outline;
                }
                else
                {
                    shadow = s;
                }
            }

1 个答案:

答案 0 :(得分:0)

GetComponent将始终返回所请求类型的第一个可用成员。

您需要使用“获取组件”来获取多个组件。这是https://unitygem.wordpress.com/getcomponent-in-c/

的示例
using UnityEngine;
using System.Collections;

public class Health : MonoBehaviour
{
     private Force [] scripts = null;
     [SerializeField] private int health = 5;

     private void Start()
     {
         this.scripts = this.gameObject.GetComponents<Force>();
     }

     private void Update()
     {
         if (Input.GetKeyDown(KeyCode.Space))
         {
             for (int i = 0; i < this.scripts.Length; i++)
             {
                 if(this.scripts[i].ReportForce())
                 {
                     this.health += 5;
                 }
             }                              
         }
     }
}