当前位置:网站首页>Essential C# scripting skills for Unity developers
Essential C# scripting skills for Unity developers
2022-08-11 08:11:00 【is a small A】
- 注释代码
Ctrl+K+C组合键可快速注释选中代码块或光标所在处代码行,Ctrl+K+U取消注释
- 对齐代码
按下Ctrl+K+F组合键可快速将选中代码块或光标所在处代码与上下文对齐
- 比较距离
将两点直接的距离与一个固定距离进行比较时,可使两点相减后取平方(即sqrMagnitude),然后用该值与某个距离值的平方进行比较.不建议使用Vector3.Distance方法获取两点之间的距离,然后与给定的距离值进行比较.因为Vector3.Distance(a,b)相当于(a-b).magnitude,即求平方根,而sqrMagnitude方法省去了求平方根的操作,所以比magnitude执行快,代码如下:
//建议使用:
Vector3 a = new Vector3(1, 1, 0);
Vector3 b = new Vector3(0, 0, 0);
float value=1.0f;
if((a-b).sqrMagnitude<value*value)
{
}
//不建议:
if(Vector3.Distance(a,b)<value)
{
}
- 移动代码行
按下Alt+键盘上/下键,即可使鼠标光标所在代码行上移/下移
- 自定义脚本模板
在你Unity版本安装目录下依次打开:Editor/Data/Resources/ScriptTemplates即可看到一堆脚本模板,选择你常用的脚本模板进行修改
- 随机获取布尔值
Unity里面的随机类Random中使用Random.value可以返回0~1之间的随机数,所以可以让其返回值与0.5f进行比较,就可以获取一个随机布尔值True或false,有点类似于JAVArandom class in
- 字符串性能优化
Certain strings do not change throughout the project and are frequently used,可将其存储在静态只读变量中,从而节省内存分配
static readonly string Fire1="Fire1";
void Update(){
Input.GetAxis(Fire1);
//不建议直接使用字符串
Input.GetAxis("Fire1");
}
- Initialize the cached component reference
When a component needs to be accessed frequently,可以在程序初始化时获取到该组件的引用,而不是在需要时才去获取,也就是减少使用GetComponent< T>(),从而避免由于重复获取引起的性能开销
private MeshRenderer mesh;
private void Awake()
{
mesh = GetComponent<MeshRenderer>();//初始化时提前缓存组件引用
}
void Update()
{
mesh.material.color = Color.red;
}
- Turn on Find and Replace mode
按下Ctr+F组合键可快速打开查找模式:(可选择当前文档或整个项目等查找匹配字符串)
- Navigate to a function or variable
鼠标光标放置在变量或函数方法处,按下F12可快速定位到其定义的代码行
- Visual StudioStatement auto-completion
使用VS写脚本时,输入 if、for、switch、foreach、try、while等语句后可双击Tab键完成语句补全
- 风格化Debug.Log的输出信息
使用debug.log输出字符串信息时,可以用富文本标记来强调内容
Debug.Log("<color=green>程序初始化加载资源</color>"+"bundle is loading");
- Find all references to a function or variable
鼠标光标放置在变量或函数处,按下Shift+F12组合键可快速查看其所有引用,单击某一引用即可定位到其代码行
- Scripts can be executed without being attached to a game object
一般来说,脚本都是要挂载到游戏对象上才能执行,但Unity提供了一个方法可以不用挂载脚本到游戏对象上也可以在程序运行时执行某个方法的语句.只需要在脚本的方法声明[RuntimeInitializeOnLoad(RuntimeInitializeLoadType.BeforeSceneLoad)] 即可,常用于程序初始化前做一些额外的初始化工作,代码如下:
(注意:必须是静态方法上声明才会生效)
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
private static void AfterSceneInit()
{
Debug.Log("场景加载之后执行");
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void BeforeSceneInit()
{
Debug.Log("场景加载之前执行");
}
- Compare Tagmethod to compare game objects
当使用到游戏对象的标签Tag进行比较时,从性能上考虑,建议使用CompareTag方法,而不用=去进行判断
if(gameObject.CompareTag("Player")){}
//等效于
if(gameObject.tag=="Player"){}
- 数据类型struct和class的序列化
The data type needs to be givenstruct和Class在面板上赋值,可以在struct和Class声明前添加[System.Serializable]
[System.Serializable]
public class UIData
{
public Text txt;
public Image IMG;
}
[System.Serializable]
public struct ObjData
{
public Transform pos;
public string name;
}
public class NewBehaviourScript : MonoBehaviour
{
public UIData mgUIData;
public ObjData myObjData;
}
- 高亮显示Debug.LogCorresponds to the game object
使用Debug.Log方法输出信息时,可将gameObject作为此方法的第二个参数,当程序运行时,单击Console面板中对应的输出信息,可在Hierarchy面板中高亮显示挂载了此脚本的游戏物体
private void Awake()
{
Debug.Log("程序初始化", gameObject);
}
- 检查脚本中空的Start和Updata函数
检查空的MonoBehavior Start和Update方法,无论你有无写逻辑,它Start函数都会执行一次,Update函数也是会每帧执行一次.如果没有逻辑实现就将其删掉,因为跑空函数多少会损耗效率
- 养成写成#region和#endregion的好习惯
写代码除了养成写注释的好习惯外,也要养成写#region和#endregion 的好习惯,当你的代码有成百上千,甚至更多行时,使用该语句可将两者之间包含的代码块折叠,方便阅读
以上就是我总结的UnityDevelop essential scripting skills,如果还想了解UnityFor compilation skills, see my previous article,If you have any other questions, please feel free to message me privately
边栏推荐
- 分门别类输入输出,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang基本数据类型和输入输出EP03
- LoRa芯片的特征
- Kaldi语音识别工具编译问题记录(踩坑记录)
- Dynamic Agent Learning
- C Primer Plus(6) 中文版 第1章 初识C语言 1.1 C语言的起源 1.2 选择C语言的理由 1.3 C语言的应用范围
- RestTemplate工具类
- Distributed Lock-Redission - Cache Consistency Solution
- 1.2-误差来源
- Break pad source code compilation--refer to the summary of the big blogger
- Creo9.0 特征的成组
猜你喜欢
The easiest trick to support quick renaming of various files
[C语言] sscanf如何实现sscanf_s?
1106 2019 Sequence (15 points)
1091 N-Defensive Number (15 points)
JRS303-Data Verification
1046 punches (15 points)
Write a resume like this, easy to get the interviewer
小目标检测3_注意力机制_Self-Attention
关于#sql#的问题:怎么将下面的数据按逗号分隔成多行,以列的形式展示出来
【TA-霜狼_may-《百人计划》】图形3.7.2 command buffer简
随机推荐
About # SQL problem: how to set the following data by commas into multiple lines, in the form of column display
Find the latest staff salary and the last staff salary changes
Swagger简单使用
支持各种文件快速重命名最简单的小技巧
matplotlib
查找最新人员工资和上上次人员工资的变动情况
Four operations in TF
【实战系列】OpenApi设计规范
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
高德能力API
CSDN21天学习挑战赛——封装(06)
go-grpc TSL authentication solution transport: authentication handshake failed: x509 certificate relies on ... ...
LoRa芯片的特征
go sqlx 包
AUTOSAR从入门到精通番外篇(八)-C语言常用技巧50个
麒麟V10系统打包Qt免安装包程序
流式结构化数据计算语言的进化与新选择
Kotlin算法入门求回文数数算法优化二数字生成规则
[C语言] sscanf如何实现sscanf_s?
Use tf.argmax in Tensorflow to return the index of the maximum value of the tensor along the specified dimension