统一ui和collider2d

时间:2018-12-23 19:54:07

标签: c# unity3d collider

这是一个简单函数的相当长的代码,但是我似乎不知道如何缩短它。有什么建议吗?

这是一个简单的脚本,我为一个初学者项目创建了一个脚本,然后将其放置在玩家对象中,同时包含了body2d和boxcollider2d,是的,它起作用了,并且所有这些都切换了按钮游戏对象,这正是我想要的在某种意义上,但我希望它仅使用一个按钮。如果您能对此有所帮助,我将不胜感激。

//different button objects
public GameObject smithbutton;
public GameObject innbutton;

private void OnTriggerEnter2D(Collider2D col)
{
//debugs which collider player is in
    if (col.gameObject.name == "Blacksmith")
    {
        Debug.Log("This is the Blacksmith");
    }
    if (col.gameObject.name == "Inn")
    {
        Debug.Log("This is the Inn");
    }
}

private void OnTriggerStay2D(Collider2D col)
{
//once playerobject stays, button will toggle till player leaves
    if (col.gameObject.name == "Blacksmith")
    {
        Debug.Log("still on the Blacksmith's door");
        smithbutton.SetActive(true);
    }
    if (col.gameObject.name == "Inn")
    {
        Debug.Log("still on the Inn's door");
        innbutton.SetActive(true);
    }
}

private void OnTriggerExit2D(Collider2D col)
{
//once playerobject exits, button will toggle and disappear
    if (col.gameObject.name == "Blacksmith")
    {
        smithbutton.SetActive(false);
    }
    if (col.gameObject.name == "Inn")
    {
        innbutton.SetActive(false);
    }
}

2 个答案:

答案 0 :(得分:0)

您不需要OnTriggerStay,可以在OnTriggerEnter中执行此操作并摆脱Stay函数。

-20(%rbp)

答案 1 :(得分:0)

由于该功能非常简单,因此您无能为力。您可以做得更好,但仍然可以减少一些限制。如果您创建更多旅馆或更多铁匠,则使用标签代替名称将是未来的证明。使用对撞机调用方法可以使您轻松扩展功能。我通常会将每张支票本人添加到客栈和铁匠铺,他们会寻找球员。

//different button objects
[SerializeField] private GameObject smithbutton;
[SerializeField] private GameObject innbutton;

private void OnTriggerEnter2D(Collider2D col)
{
//debugs which collider player is in
    if (col.gameObject.tag == "Blacksmith")
    {
        ButtonActivationToggle(smithbutton, col);
    }
    if (col.gameObject.tag == "Inn")
    {
        ButtonActivationToggle(innbutton, col);
    }
}

private void OnTriggerExit2D(Collider2D col)
{
//once playerobject exits, button will toggle and disappear
    if (col.gameObject.tag == "Blacksmith")
    {
        ButtonActivationToggle(smithbutton, col);
    }
    if (col.gameObject.tag == "Inn")
    {
        ButtonActivationToggle(innbutton, col);
    }
}

public void ButtonActivationToggle(GameObject button, Collider2D collider)
{
    bool tmp = false;
    tmp = button.activeInHierarchy ? false : true;
    button.SetActive(tmp);
    if (button.activeInHierarchy)
    {
        Debug.Log("This is the " + gameObject.collider.tag)
    }
}