Unity3D之NGUI基础5.1:代码控制UISprite
前文:https://blog.****.net/Jaihk662/article/details/86772975(UISprite显示图片)
一、UI其它创建方案
可以通过 NGUI→Create→2D UI 直接创建 UI Root,如下:
2D UI 呈现灰色(不可创建)是因为一个Scene只能存在一个2D UI Root
除此之外,直接新建子物体方法如下:图片中的文字就是背景图的子物体
二、代码控制UISprite
目的:用脚本实现创建物体,添加脚本,设置属性等步骤
一些有用的API:
- xxx.GetComponent<Transform>().SetParent(transform):将物体xxx设置为yyy.transform的子物体
- xxx.GetComponent<Transform>().localScale = Vector3:设置物体xxx的初始点
- xxx.AddComponent<T>():给物体xxx添加组件T,返回这个组件
- Resources.Load<>:从Resources文件夹中加载资源
- UISprite xxx.method:调用组件UIsprite中的method属性,(这个API可以举一反三,调用UIsprite中的所有属性)
- ……
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Createpic : MonoBehaviour // UI Root的脚本
{
private Transform myTran;
void Start ()
{
myTran = gameObject.GetComponent<Transform>();
GameObject pic = new GameObject("Picture"); //创建一个物体(实例化一个对象)
pic.GetComponent<Transform>().SetParent(myTran); //将pic设置为UI Root的子物体
pic.GetComponent<Transform>().localScale = new Vector3(1, 1, 1); //重置物体的位置
UISprite sp = pic.AddComponent<UISprite>(); //动态添加组件UISprite
UIAtlas atl = Resources.Load<UIAtlas>("New Atlas"); //读取图集
sp.atlas = atl; //给组件指定图集
sp.spriteName = "bg"; //给组件指定图片
sp.width = 268;
sp.height = 42;
}
void Update ()
{
}
}
将以上脚本挂到UI Root上即可