扩展Unity的方法

简介:



写更少代码的需求

当我们重复写一些繁杂的代码,或C#的一些方法,我们就想能不能有更便捷的方法呢?当然在unity中,我们对它进行扩展。

对unity的类或C#的类进行扩展有以下两点要注意:

1、这个类必须声明为static,扩展的方法也必须要声明为static

2、在使用时,就可以直接调用扩展的方法

扩展Unity的属性

Demo

using UnityEngine;
using System.Collections;

//It is common to create a class to contain all of your
//extension methods. This class must be static.
public static class ExtensionMethods
{
    //Even though they are used like normal methods, extension
    //methods must be declared static. Notice that the first
    //parameter has the 'this' keyword followed by a Transform
    //variable. This variable denotes which class the extension
    //method becomes a part of.
    public static void ResetTransformation(this Transform trans)
    {
        trans.position = Vector3.zero;
        trans.localRotation = Quaternion.identity;
        trans.localScale = new Vector3(1, 1, 1);
    }
}

 

使用方法

using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour 
{
    void Start () {
        //Notice how you pass no parameter into this
        //extension method even though you had one in the
        //method declaration. The transform object that
        //this method is called from automatically gets
        //passed in as the first parameter.
        transform.ResetTransformation();
    }
}

扩展C#的方法

为C#的集合扩展一个方法,当在调用时,就可以直接调用CFirstOrDefault

public static T CFirstOrDefault<T>(this IEnumerable<T> source)
{
    if (source != null)
    {
        foreach (T item in source)
        {
            return item;
        }
    }

    return default(T);
}

文档资料

文档:http://unity3d.com/learn/tutorials/modules/intermediate/scripting/extension-methods


本文转自赵青青博客园博客,原文链接:http://www.cnblogs.com/zhaoqingqing/p/4629336.html,如需转载请自行联系原作者

相关文章
|
安全 图形学
|
存储 JSON API
Qt开发技术:Qt的动态静态插件框架介绍和Demo
Qt开发技术:Qt的动态静态插件框架介绍和Demo
Qt开发技术:Qt的动态静态插件框架介绍和Demo
|
搜索推荐 Linux C#
Unity基础
Unity是什么,Unity是一个游戏开发引擎,他功能强大,学习简单,炉石传说,王者荣耀等游戏就是利用Unity引擎开发出来的
259 0
Unity基础
|
Go C# 图形学
Unity3D中对系统类进行扩展教程(简化代码逻辑)
Unity中对系统类进行扩展的方法 Unity扩展系统类,简化代码 本文提供全流程,中文翻译。 助力快速完成 Unity 对系统类进行扩展,添加函 新建一个脚本,名称随意 类必须设为静态 Static ,函数同样(这样才能通过其他类,直接访问到扩展函数) 形参为 this + 需要扩展的类 此时,我们通过 transform.
1455 0
|
JSON 数据格式
Unity 基础之LitJSON
最近接手一个项目,在项目中有用到Json的地方,根据网上找到的资料 客户端配置文件优化策略,综合评定发现LitJson还不错,于是找到Json下载的网站的网站下载对应的Json,进入LitJson后尽然提示我 404! WTF?!!!我可是会科学上...
1543 0
|
安全 C# 图形学
Unity C#基础之 多线程的前世今生(下) 扩展篇
在前面两篇Unity C#基础之 多线程的前世今生(上) 科普篇和Unity C#基础之 多线程的前世今生(中) 进阶篇中,相信大家对多线程有了一定的了解,这篇再详细的聊一聊在使用多线程中需要注意的地方~ 示例工程下载Unity 2017.
1149 0
|
C# 图形学
Unity C#基础之 特性,一个灵活的小工具
特性在框架中的应用也是很普遍,只需要在相应的类、字段、属性、函数等上面加上这个特殊的小东西就会在相应的元素上面添加一些特殊的应用效果,下面就为大家简单的介绍下特性的原理和应用场景 在往期的博客中有介绍过一些特性 Unity Debug输出到屏幕并保存到本地中的Conditional("EnableLog")特性 Unity Attributes中Unity自带的特性 Obsolete、Serializable等 下面咱们来聊一聊特性到底是个什么,都能干什么?为什么说它是一个灵活的小工具。
1844 0