在C#中如何引用Unity Sprite的宽度 解决程序化生成关卡瓦片重叠问题
实现方案
核心逻辑
Unity 中 GameObject 没有内置的 width、height 属性,你需要从地面预制件挂载的 SpriteRenderer 组件中获取瓦片的实际世界单位尺寸,再根据尺寸计算每个瓦片的生成坐标即可避免重叠。
推荐使用整数计数控制瓦片生成数量,再通过计数乘以瓦片尺寸得到对应坐标,避免浮点循环可能出现的精度误差。
修改后代码
public class LevelGenerator: MonoBehaviour { [SerializeField] int width, height; // 此处为生成的瓦片横向、纵向数量 [SerializeField] GameObject ground; void Start() { Generator(); } public void Generator() { // 获取地面瓦片的SpriteRenderer组件,读取世界坐标下的实际宽高 SpriteRenderer groundSr = ground.GetComponent<SpriteRenderer>(); float tileWidth = groundSr.bounds.size.x; float tileHeight = groundSr.bounds.size.y; for (int xCount = 0; xCount < width; xCount++) { for (int yCount = 0; yCount < height; yCount++) { // 计算当前瓦片的生成坐标 float posX = xCount * tileWidth; float posY = yCount * tileHeight; /* 如果你的Sprite的Pivot为默认的中心点(0.5,0.5),需要加偏移对齐左下角: posX += tileWidth / 2; posY += tileHeight / 2; */ Instantiate(ground, new Vector2(posX, posY), Quaternion.identity); } } } }
补充说明
- 若你对瓦片对齐有特殊要求,可以直接调整地面Sprite的Pivot参数,调整后不需要修改坐标计算逻辑就能实现不同的对齐效果
bounds.size已经自动计算了预制件的缩放、Sprite的Pixels Per Unit参数,不需要手动做单位换算
内容的提问来源于stack exchange,提问作者user2669412
相关产品推荐
相关产品推荐

