Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on Dec 8, 2022, between 7 am & 7 pm EST, in the DOTS Dev Blitz Day 2022 - Q&A forum, Discord, and Unity3D Subreddit to learn more about DOTS directly from the Unity Developers.
    Dismiss Notice
  3. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Question Draw a border around an image shape witch has a BoxCollider2D

Discussion in 'Scripting' started by frino7, Nov 21, 2022.

  1. frino7

    frino7

    Joined:
    Nov 2, 2022
    Posts:
    5
    Hello,

    I have a prefab, which has an image component. After instantiate it in runtime, I add a BoxCollider2D to it. And after it I would like to add a red border to that image rectangle.
    I tried to determine the boxcollider rectangle
    Code (CSharp):
    1.  
    2. go.AddComponent<BoxCollider2D>();
    3. bc = go.GetComponent<BoxCollider2D>();
    4. bc.size = new Vector2(image.rectTransform.rect.width, image.rectTransform.rect.height);
    5.  
    because it is always around the image and wanted to draw that with a line renderer but it doesn’t worked somehow. Is that theoretically workable?
    I checked the bounds min and max positions and tried to set to the line renderer positions but also not worked.

    How can I do that any idea?
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,254
    BoxCollider2D and Image are pretty fundamentally incompatible (unless this is a world space canvas).

    Image will be a UI element in screen space and BoxCollider2D will live in world space. Are you sure you don't want a SpriteRenderer?
     
    frino7 likes this.
  3. frino7

    frino7

    Joined:
    Nov 2, 2022
    Posts:
    5
    Good to know that. Thanks!
    This image adding UI thing is on a UI canvas set to Screen Space Overlay. I need to finish this until next week.
    I not really need a BoxCollider2D, I just thought if I add that to the image I can easily set its boundary to a line renderer (as I saw it is not really so easy) and show like the image would have benn selected. If I could make some other way to make an image "selection" if I add a colored border to the image (not the outline, but the rectangle, because this images are 512x512 px and when I scale the image and I would like to draw a border updated and aligned with the image).
     
  4. frino7

    frino7

    Joined:
    Nov 2, 2022
    Posts:
    5
    Finally I rewrote it with SpriteRenderer. Works great! Thanks again!:)