使用Unity C#中的数组的GetComponent,如何为数组中的项目调用GetComponent

时间:2018-10-24 23:40:56

标签: c# unity3d

BoardManager类:

        public void HighlightTile()
        {
            Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            foreach (GameObject g in GameBoard) //g is the tile prefab with SpriteInfo attached to it
            {
                Vector2 min = g.GetComponent<SpriteRenderer>().bounds.min;
                Vector2 max = g.GetComponent<SpriteRenderer>().bounds.max;
                if (mousePos.x > min.x && mousePos.y > min.y && mousePos.x < max.x && mousePos.y < max.y)
                {
                    g.GetComponent<SpriteRenderer>().color = Color.red;
                }
            }
        }

Sprite信息类:

public Vector2 min;
public Vector2 max;


public Vector2 FindMin
{
    get
    {
        return GetComponent<SpriteRenderer>().bounds.min;
    }
}

public Vector2 FindMax
{
    get
    {
        return GetComponent<SpriteRenderer>().bounds.max;
    }
}

随机创建的瓷砖预制件的SpriteInfo

Pic

每当我在HighlightTile方法中Debug.Log min和max时,两者均返回0。但是,每当我在SpriteInfo类中对其进行调试时,它都会返回正确的数字。在编辑器上,每个创建的图块克隆中也包含正确的信息,只是当我在“突出显示”图块中将其称为0时。我认为min = g.GetComponent()。bounds.min&最高g是已附加SpriteInfo的图块预制板。如何在HighlightTile方法中获取正确的信息?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试一下:

    public void HighlightTile()
    {
        Vector3 mouse = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        foreach (SpriteInfo sprite in GetComponentsInChildren<SpriteInfo>())
        {
            SpriteRenderer renderer = sprite.GetComponent<SpriteRenderer>();
            if (renderer.bounds.Contains(mouse))
                renderer.color = Color.red;
        }
    }

您还可以向每个精灵添加BoxCollider并使用OnMouseDown