public class ABCD : MonoBehaviour
{
[SerializeField]
Outline outline;
[SerializeField]
Shadow shadow;
private void Start()
{
outline = GetComponent<Outline>();
shadow = GetComponent<Shadow>();
}
}
我们知道Outline
是这样的实现Shadow
。
所以当我打电话
shadow = GetCompoent<Shadow>();
因为Ouline
也是Shadow
,所以有可能找到大纲组件。
而且我不能放弃该组件以保持引用。 因为我的代码完全像这样
//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;
}
}
答案 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;
}
}
}
}
}