Olivier Pons
Olivier Pons

Reputation: 15778

How to compare child object based on their transform object?

I'm generating a lot of objects via this function:

private GameObject CreateGhost(Transform p, float r, float g, float b)
{
    GameObject result = Instantiate(
        gameObject, Vector3.zero, Quaternion.identity
    );
    Transform ghost_t = result.transform;
    RectTransform ghost_rt = result.GetComponent<RectTransform>();
    ghost_t.SetParent(p, false);
    ghost_rt.anchorMin = new Vector2(0f, 0f);
    ghost_rt.anchorMax = new Vector2(0f, 0f);
    ghost_rt.pivot = new Vector2(0f, 0f);
    ghost_rt.localScale = new Vector3(1f, 1f, 1f);

    Image m = result.GetComponent<Image>();
    m.color = new Color(r, g, b, 0.7f);

    return result;
}

Knowing that the parameter Transform p is always the same, there are a lot of children in the same "parent" object.

When the user clicks on an object, I make it move, and I want to see if its Rect overlaps another rect (NB: I dont want to use BoxCollider2D for now).

My loop is like that:

RectTransform ghost_rt = Ghost.GetComponent<RectTransform>();
Rect ghost_r = new Rect(ghost_rt.anchoredPosition, 
    new Vector2(ghost_rt.rect.width, ghost_rt.rect.height));
bool overlaps = false;
foreach (Transform child_t in Dst.transform) {
    if (!GameObject.ReferenceEquals(child_t, ghost_rt)) {
        RectTransform rt = child_t.GetComponent<RectTransform>();
        Rect cmp_r = new Rect(rt.anchoredPosition,
            new Vector2(rt.rect.width, rt.rect.height));
        DebugText.text += "cmp_r:" + cmp_r + "\n";
        if (cmp_r.Overlaps(ghost_r)) {
            overlaps = true;
            break;
        }
    }
}

This comparison doesn't work: (!GameObject.ReferenceEquals(child_t, ghost_rt)).

I tried that one too without success: (!GameObject.ReferenceEquals(child_t.parent, ghost_rt.parent))

What is the method to know if I can compare with the other child (= different from the current object)?

Upvotes: 0

Views: 124

Answers (1)

joreldraw
joreldraw

Reputation: 1736

You can use Rect.Overlaps to know if 1 rect are overlapping other:

child_t.Overlaps(ghost_rt.rect)

Upvotes: 1

Related Questions