1.在NGUI的UI Root里添加一个空物体,命名为BGStory,用于存放sprite。
2.创建一个C#文件,将其拖入Main Camera中。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BGSController : MonoBehaviour
{
private UIAtlas bgsAtlas; //背景图集
private Transform BGUI; //空的父物体
void Start ()
{
BGUI = GameObject.Find("BGStory").GetComponent<Transform>();
bgsAtlas = Resources.Load<UIAtlas>("BGStory");
CreateBGS();
}
void Update () {
}
void CreateBGS()
{
for (int i = 7; i > 0; i--) //七张图片
{
string str= i.ToString();
GameObject one = new GameObject(); //创建一个物体
one.name = str; //设置名字为i
one.transform.SetParent(BGUI); //设置为父物体的子物体
BoxCollider box= one.AddComponent<BoxCollider>(); //添加一个box碰撞体组件
box.isTrigger=true;
one.AddComponent<BGSClick>(); //添加点击事件的代码文件
one.AddComponent<UIButton>().tweenTarget = one.gameObject; //添加UIBUTTON组件,并将tweenTarget设置为本物体
UIButton button = one.GetComponent<UIButton>();
button.normalSprite = button.name; //将uibutton中的normal颜色注释掉
UISprite sp= one.AddComponent<UISprite>(); //添加UISPRITE组件
box.size = new Vector3(1024,576,0); //碰撞体的SIZE
sp.atlas = bgsAtlas; //指定图集
sp.MakePixelPerfect(); //动态设置snap
sp.spriteName = str;
}
}
}
3.创建一个C#文件,用于存放点击事件。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BGSClick : MonoBehaviour {
void OnClick()
{
gameObject.SetActive(false);
}
}
新手菜鸟,第一次动态创建NGUI。琢磨了一下,本来BGStory也想动态创建的,试过之后图片显示有问题,就直接创建了一个空物体。
button.normalSprite = button.name; 这一个的注释可能是不准,我是百度了一下如何使button的normal不显示的,等下查查api。
图集也可以动态创建,以后试试。