unity 游戏工具类

前言

unity 游戏工具类: 工具中提供接口,供整个游戏工程使用
工具类具体实现根据实际情况来定,如果某个方法情况使用次数多,就把他做个封装方法,也就是工具类里的方法。

查找工具类

查找游戏对象的子物体方法

    public static GameObject FindChildGameObject(GameObject parent,string childName) {
        Transform[] childGroup = parent.GetComponentsInChildren<Transform> ();
        GameObject retobj = null;
        //查找
        for (int i = 0; i < childGroup.Length; i++) {
            if (childGroup [i].name == childName) {
                retobj = childGroup [i].gameObject;
                break;
            }
        }
        return retobj;
    }

查找游戏物体方法

    //查找游戏物体
    public static GameObject FindGameObject(string objName) {
        GameObject retObj = null;
        if (objName != "")
            GameObject.Find (objName);
        return retObj;
    }
UI查找工具类
  1. 查找U IRoot下的ui对象
  2. 查找ui对象的组件
using UnityEngine;
using System.Collections;
/// <summary>
/// User interface tool.
/// 用来在UI控件上查找组件
/// </summary>
public class UITool{

    private static GameObject _uiRoot;

    public static GameObject GetUIRoot{
        get{ 
            return _uiRoot = Util.FindGameObject ("UI Root");
        }
    }

    //在objName物体上查找UI组件T
    public static T FindUI<T>(string objName,GameObject parent = null) where T : class{
        GameObject theParent = GetUIRoot;
        if (parent != null) {
            theParent = parent;
        }

        //先: 根据名字获取到游戏物体
        T retComponent = null;
        GameObject obj = Util.FindChildGameObject (theParent, objName);
        //再: 在游戏物体上查找T组件
        if (obj != null) {
            retComponent = obj.GetComponent<T> (); 
        }
        return retComponent;
    }
}

为了方便些,一般工具类都是用单例,使用静态方法,返回一个物体对象使用

先写到这,以后有时间更新:)

猜你喜欢

转载自blog.csdn.net/liaoshengg/article/details/81195916
今日推荐