【小松教你手游开发】【unity实用技能】拓展函数(给系统代码添加可直接使用的接口)

来源:互联网 发布:北大青鸟java视频教程 编辑:程序博客网 时间:2024/06/06 01:28

拓展函数的意思是给一些没有源码的脚本添加上你自己写的接口并可以直接调用。

using UnityEngine;using System.Collections;namespace ExtensionMethods{    public static class MyExtensions    {        public static void SetLocalPositionX(this Transform transform, float x)        {            Vector3 newPosition = new Vector3(x, transform.localPosition.y, transform.localPosition.z);            transform.localPosition = newPosition;        }        public static T GetSafeComponent<T>(this GameObject go)        {            T component = go.GetComponent<T>();            if (component == null)            {                CDebug.LogError("!!!error :You are finding compoent of type: " + typeof(T) + ", but found none,gameObject:" + go.name);            }            return component;        }    }}

像我上面写的这样,这样就可以直接在transform.SetLocalPositionX()来设置坐标。

而GetSafeComponent()是防止你在找脚本的时候出现空引用而不知道问题在哪。

而这里需要的使用条件是在头文件里添加 using ExtensionMethods;


0 0