Search code examples
c#2dtexturesunity-game-engine

creating a 2d rectangle and applying a texture to it


I want to create a colored rectangle, my normal approach would be to create a sprite of a rectangle in the desired size, import it to unity, attach it to a game object, then attach things like physics, collision control and what not.

However, I would like to create a rectangle of random size, then give it a texture. I can't do it the old way, cause then I would have to create several thousands sprites then take a random one.

How can I create a 2d rectangle, of random size, without using any sprite?

Honestly, I don't know if this question makes sense, I might be thinking of it all wrong, I just need to know what approach I should use, I am completely at a loss here.


Solution

  • You could instantiate a cube, as since it's a 2D environment cubes render as rectangles unless rotated. The simplest way is to make a prefab of the cube you want and then instantiate it, à la Instantiate(myCube, new Vector3(0, 0), Quaternion.Euler(0, 0, 0), myParent);.

    You could also attempt to make a primitive cube and then assign its properties manually, though this is very convoluted. I'm away from home right now so it's untested, but the following method should return a cube out of a position, scale, and a color (but can be edited to accept a material):

    GameObject NewCube(Vector3 pos, Vector3 scale, Color color) {
    
        GameObject cubePrototype = GameObject.CreatePrimitive(PrimitiveType.Cube);
        cubePrototype.transform.position = pos;
        cubePrototype.transform.localScale = scale;
    
        Material materialPrototype = new Material(Shader.Find("Unlit/Color"));
        materialPrototype.color = color;
    
        Renderer cubeRenderer = new Renderer(cubePrototype.GetComponent<Renderer>());
        cubeRenderer.material = materialPrototype;
    
        return cubePrototype;
    }
    

    In your own case, simply pass three random numbers for the scale argument.