【Unity学习实践记录01】Unity NGUI动态创建sprite并添加点击事件

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。

图集也可以动态创建,以后试试。

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值