At start of my 2D unity game I want to create a new "building" (at random).

So I created a prefab named "Building" from a polygon sprite. Then I created a "Empty Game Object" named "GameManager" with a script named "GameManager" attached to it. The script looks like this:

public class GameManager : MonoBehaviour
    public GameObject Building;
    // Start is called before the first frame update
    void Start()
        var createdBuilding = Instantiate(Building, new Vector3(0, 0, 0), Quaternion.identity);
        var sprite = createdBuilding.GetComponent<SpriteRenderer>().sprite;
        Vector2[] geometry = new Vector2[6];
        geometry[0] = new Vector2(0,0);
        geometry[1] = new Vector2(0,20);
        geometry[2] = new Vector2(20,20);
        geometry[3] = new Vector2(27,20);
        geometry[4] = new Vector2(29,29);
        geometry[5] = new Vector2(16,0);
        sprite.OverrideGeometry(geometry, sprite.triangles);

The hardcoded position values are just for testing purporses. The plan is to create multible buildings but first I have to get unity to show at least one of them.

Afterwards I attached the prefab "Building" to the variable "Building" via the inspector.

But when I ran the game the sprite is shown as a Pentagon, regardless what I write into the "geometry"-Array.

So why I cant change the geometry? And is this even the right way to create buildings at startup?

  • 1
    \$\begingroup\$ Is there any reason why you are overriding the vertices but not the triangles? \$\endgroup\$ – Weckar E. Jul 6 '20 at 18:02
  • \$\begingroup\$ @Weckar E.: I really dont know what "the triangles" are. My Geometry is just an example (Ill change it so its not a triangle anymore) \$\endgroup\$ – Gener4tor Jul 6 '20 at 21:35
  • 1
    \$\begingroup\$ Maybe you should look it up or ask that question then. The documentation says it's an "Array of sprite mesh triangle indices" and "The size of the triangle array must always be a multiple of 3. The vertices connected to the triangle can be shared by simply indexing into the same vertex." so it sounds like it works just like the triangles property of a regular Unity mesh. \$\endgroup\$ – DMGregory Jul 6 '20 at 21:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.