简体   繁体   English

创建一个2d矩形并对其应用纹理

[英]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? 如何在不使用任何精灵的情况下创建随机大小的2D矩形?

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. 您可以实例化多维数据集,因为它是2D环境,除非旋转,否则多维数据集将渲染为矩形。 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); 最简单的方法是对所需的多维数据集进行预制,然后实例化它, 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. 在您自己的情况下,只需为scale参数传递三个随机数。

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 );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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