触发/碰撞时最简单的方法来定位GameObjects属性?

时间:2017-05-12 09:34:47

标签: c# unity3d unity5

如果我有触发器或碰撞,我想要定位该gameObject,并且可以访问每个附加脚本的属性。我设法做到这一点,但我知道必须有一个更好的方法吗?

这里我想定位附加到标记为“BoxManager”的触发游戏对象的脚本,然后BoxManager的属性“isHeld”如果在触发器/碰撞交互时动态选择目标,我必须使用目标对象,但还有更好的方法来完成剩下的工作吗?

void OnTriggerStay2D(Collider2D target)
{
    if (target.gameObject.tag == "Box")
    {
        if (target.attachedRigidbody.GetComponent<BoxManager>().isHeld == false)
        {
            target.attachedRigidbody.AddForce(transform.right * thrust);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

首先,target.attachedRigidbody.GetComponent<BoxManager>()完全没必要且多余。我发现人们甚至会使用target.attachedRigidbody.gameObject.transform.GetComponent<BoxManager>();这样的代码做得更糟。那是做同样的事情,因为它们都附加在一个GameObject上。

您可以而且应该只是target.GetComponent<BoxManager>();

至于在碰撞过程中一直使用GetComponent函数来获取另一个脚本,那很好。这是在碰撞期间获取另一个附加到GameObject的脚本的最简单方法,然后才能访问该脚本中的变量。

尽管如此,我觉得你必须在GetComponent中为此OnTriggerStay2Dvoid OnTriggerStay2D(Collider2D target){} 。当你有太多的脚本需要检查时,它会变得更烦人。

这是你的碰撞功能:

BoxManager

你需要在碰撞后从目标访问你的Dictionary脚本....

一个棘手的方法是使用Start。在Collider2D函数中初始化词典并使用BoxManager作为键,Collider2D作为值。

在游戏过程中使用BoxManagerDictionary<Collider2D, BoxManager> scriptID = new Dictionary<Collider2D, BoxManager>(); 实例化和销毁GameObjects时更新此词典。

这样的事情:

TryGetValue

然后在碰撞功能中,使用targetBoxManager变量作为获取void OnTriggerStay2D(Collider2D target) { if (target.CompareTag("Box")) { BoxManager result; scriptID.TryGetValue(target, out result); if (!result.isHeld) { } } } 组件的键。

BoxManager

事实上,如果您%100确定此对象附加了TryGetValue脚本,您可以在没有void OnTriggerStay2D(Collider2D target) { if (target.CompareTag("Box")) { BoxManager result = scriptID[target]; } } 的一行代码中执行此操作功能:

BoxManager

通过使用上面的target.CompareTag,您可以减少在没有target.gameObject.tag脚本的情况下检测对象的机会。请注意我将target.CompareTag更改为target.CompareTag的方式。它建议使用BoxManager result = scriptID[target];

现在使用target.CompareTag("Box")作为后卫,使用 TryGetValue简化了代码,这样您就不必使用ContainsKeyDictionary<Collider2D, BoxManager> scriptID = new Dictionary<Collider2D, BoxManager>(); public BoxManager boxManagerPrefab; void Start() { //Register your BoxManager instances to the Dictionary for (int i = 0; i < 5; i++) { BoxManager bc = Instantiate(boxManagerPrefab) as BoxManager; //Use Isntance ID of the Script as id Collider2D cld2D = boxManagerPrefab.GetComponent<Collider2D>(); scriptID.Add(cld2D, bc); } } void OnTriggerStay2D(Collider2D target) { if (target.CompareTag("Box")) { BoxManager result = scriptID[target]; if (!result.isHeld) { target.attachedRigidbody.AddForce(transform.right * thrust); } } } 功能。

以下是整个脚本的示例:

easy_install boto3