简体   繁体   中英

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.

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.

The way to go about this is to add a sprite to your project then attach a script to that sprite that produces two random numbers one for the length and then one for the width.

void Awake(){

    Vector3 scale = new Vector3( width, height, 1f );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM