2d图片依次排列在屏幕中间(SpriteRenderer)
程序员文章站
2023-10-16 17:59:20
如图所示: C#代码: lua代码: ......
如图所示:
c#代码:
1 using system.collections; 2 using system.collections.generic; 3 using unityengine; 4 5 public class spriterenderertest : monobehaviour { 6 list<transform> list = new list<transform>(); // 存储父物体的子对象 7 list<float> rendererwidthlist = new list<float>(); // 存储子对象的宽度 8 private vector3 centerpos = vector3.zero; // 中心位置 9 private float offset = 0.2f; //偏移量 10 private float length = 0.0f; // 初始化长度 11 12 void start () { 13 // 遍历所有子对象 14 for (int i = 0; i < gameobject.transform.childcount; i++) { 15 var child = gameobject.transform.getchild(i); 16 var width = child.getcomponent<spriterenderer>().sprite.bounds.size.x; 17 if (i < gameobject.transform.childcount - 1) 18 { 19 length += width + offset; 20 } 21 else { 22 length += width; 23 } 24 list.add(child); 25 rendererwidthlist.add(width); 26 } 27 var startx = centerpos.x - length / 2.0f; //第一个子对象的左边界 28 foreach (var child in list) 29 { 30 int index = 0; 31 child.transform.position = new vector3(startx + rendererwidthlist[index] / 2.0f, 0, 0); 32 startx = startx + offset + rendererwidthlist[index]; 33 index += 1; 34 } 35 } 36 }
lua代码:
1 -- 创建数组 2 local parent = ugameobject.find("parent") 3 local objectlist = {} 4 local rendererwidthlist = {} 5 for i = 1, parent.transform.childcount do 6 local child = parent.transform:getchild(i - 1) 7 local renderer = child:getcomponent(typeof(uspriterenderer)) 8 local width = renderer.sprite.bounds.size.x 9 table.insert(objectlist, child) 10 table.insert(rendererwidthlist, width) 11 end 12 13 local length = 0 -- 初始化长度 14 local offset = 0.2 -- 间隔 15 for i = 1, #objectlist do 16 local obj = objectlist[i] 17 local width = rendererwidthlist[i] 18 if i == #objectlist then 19 length = length + width 20 break 21 end 22 length = length + width + offset 23 end 24 25 local centerpos = vector3.zero -- 中心位置 26 local startx = centerpos.x - length / 2 -- 初始位置 27 28 for i = 1, #objectlist do 29 local obj = objectlist[i] 30 local width = rendererwidthlist[i] 31 obj.transform.position = vector3(startx + width / 2, 0, 0) 32 startx = startx + width + offset 33 end
上一篇: java8 Lambda 表达式和函数式接口快速理解
下一篇: C#左移运算符