Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by TharosTheDragon · Sep 24, 2017 at 09:26 PM · 2dscripting problemcanvasline renderervector graphics

How do I draw simple shapes?

I want to be able to draw both solid shapes and lines, much like how Flash has fills and strokes. My dilemma is that I have to decide whether to draw them on a canvas or not. I can draw a solid shape on a canvas using UnityEngine.UI.Graphic like this:

 using UnityEngine;
 using UnityEngine.UI;
 
 [ExecuteInEditMode]
 public class UpArrow : Graphic
 {
     public float size;
 
     protected override void OnPopulateMesh ( VertexHelper vh )
     {
         if ( shouldDraw )
         {
             vh.Clear ();
 
             Vector2 [] vecs = {
                 
                 new Vector2 ( 0, halfSize ),
                 new Vector2 ( -halfSize, 0 ),
                 new Vector2 ( -quarterSize, 0 ),
                 new Vector2 ( -quarterSize, -halfSize ),
                 new Vector2 ( quarterSize, -halfSize ),
                 new Vector2 ( quarterSize, 0 ),
                 new Vector2 ( halfSize, 0 )
             };
 
             for ( int i = 0 ; i < vecs.Length ; i++ )
             {
                 vh.AddVert ( vecs [ i ], color, Vector2.zero );
             }
 
             vh.AddTriangle ( 0, 1, 6 );
             vh.AddTriangle ( 2, 3, 4 );
             vh.AddTriangle ( 4, 5, 2 );
         }
     }
 
     protected override void Awake ()
     {
         base.Awake ();
 
         halfSize    = size / 2;
         quarterSize    = size / 4;
     }
 
     private bool shouldDraw = true;
     private float halfSize;
     private float quarterSize;
 
 }
 

However, if I want to draw lines with UnityEngine.LineRenderer I can't use a canvas. And any solid shapes I draw using a CanvasRenderer will automatically go on top of any lines.

LineRenderer seems appealing because it gives the option of rounded end caps, which can be used to draw a solid circle if you make a line with its two ends in the same position. Is there any way to get that kind of functionality on a canvas? Or is there any way to get the functionality of Graphic outside of a canvas?

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image $$anonymous$$ · Sep 25, 2017 at 06:10 AM 0
Share

You could create an empty sprite and override its geometry to any shape you can make out of triangles, if you want I could give you some examples.

avatar image TharosTheDragon · Sep 25, 2017 at 01:34 PM 0
Share

Yes, I'd like some examples. I was thinking of using sprites too. Is there a way to programmatically draw shapes on a transparent sprite?

1 Reply

· Add your reply
  • Sort: 
avatar image
6
Best Answer

Answer by $$anonymous$$ · Sep 25, 2017 at 09:16 PM

Here's a script that will create a polygon, in this example I've set it to a rough pentagon

 using System.Collections.Generic;
 using UnityEngine;
 
 public class DrawShape : MonoBehaviour {
 
     void Start()
     {
         Vector2[] vertices = new Vector2[] { new Vector2(1, 1), new Vector2(.05f, 1.3f), new Vector2(1, 2), new Vector2(1.95f, 1.3f), new Vector2(1.58f, 0.2f), new Vector2(.4f, .2f) };
         ushort[] triangles = new ushort[] { 0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 5, 0, 5, 1 };
         DrawPolygon2D(vertices, triangles, Color.red);
     }
 
     void DrawPolygon2D(Vector2[] vertices, ushort[] triangles, Color color)
     {
         GameObject polygon = new GameObject(); //create a new game object
         SpriteRenderer sr = polygon.AddComponent<SpriteRenderer>(); // add a sprite renderer
         Texture2D texture = new Texture2D(1025, 1025); // create a texture larger than your maximum polygon size
 
         // create an array and fill the texture with your color
         List<Color> cols = new List<Color>(); 
         for (int i = 0; i < (texture.width * texture.height); i++)
            cols.Add(color);
         texture.SetPixels(cols.ToArray());
         texture.Apply();
 
         sr.color = color; //you can also add that color to the sprite renderer
 
         sr.sprite = Sprite.Create(texture, new Rect(0, 0, 1024, 1024), Vector2.zero, 1); //create a sprite with the texture we just created and colored in
 
         //convert coordinates to local space
         float lx = Mathf.Infinity, ly = Mathf.Infinity;
         foreach (Vector2 vi in vertices)
         {
             if (vi.x < lx)
                 lx = vi.x;
             if (vi.y < ly)
                 ly = vi.y;
         }
         Vector2[] localv = new Vector2[vertices.Length];
         for (int i = 0; i < vertices.Length; i++)
         {
             localv[i] = vertices[i] - new Vector2(lx, ly);
         }
 
         sr.sprite.OverrideGeometry(localv, triangles); // set the vertices and triangles
 
         polygon.transform.position = (Vector2)transform.InverseTransformPoint(transform.position) + new Vector2(lx, ly); // return to world space
     }
 }

You can feed it whatever vertices you want and map the triangles, here's a visualization

alt text


polygons.png (7.8 kB)
Comment
Add comment · Show 7 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image elliotching · Mar 18, 2018 at 01:54 PM 0
Share

is this cannot draw on UI Canvas? I need something can draw on Canvas only but not in world space. Can you show me how? Thanks.

avatar image Bunny83 elliotching · Mar 18, 2018 at 04:15 PM 0
Share

The original question didn't want to use the UI canvas if you read it carefully since he wanted to use the linerenderer. This creates a usual mesh object. If you want to ask a different question, please ask a question and do not bump unrelated questions.

avatar image Barreiros93 · May 25, 2018 at 01:50 PM 1
Share

what would be the best strategy to draw this 2d shape but have more control, saying things like draw only the stroke without the fill?

avatar image VishweshVichu · Apr 17, 2020 at 11:31 AM 0
Share

This won't work for a circle, right? Or is there any way to workaround?

avatar image TharosTheDragon VishweshVichu · Apr 18, 2020 at 03:02 AM 0
Share

I actually created a class that draws any polygon and lets you customize the number of vertices, just like when making 3D shapes in Blender. It will never be a "true" mathematical circle but if you give it so many vertices that each side is smaller than a pixel then who's to know?

avatar image VishweshVichu · Apr 20, 2020 at 08:51 AM 0
Share

For a circle, This won't work..., right? or is there a way to workaround?

avatar image urkourbieta · Apr 15, 2021 at 07:32 AM 0
Share

I can see it in the Scene but not in the Game. I assume it's because of the Z axys's coordinate, how can I change it? Also I would like to draw the polygon without filling color, only the borders, but I didn't manage to get that working. Thanks in advance @$$anonymous$$ .

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

180 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Move the line renderer in a circle with only left and right arrow keys 1 Answer

Line Renderer and Canvas Group? 1 Answer

UDP app signature? 1 Answer

How to Rotate 2D Object Without Changing Axis Orientation? 1 Answer

Destroy script turns objects into ghosts 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges