核心模块
Core要做好,底子打好,分块都很复杂,但是有相似的地方,实现这种的抽象
虚幻引擎的蓝图,
文件目录
随机ID的生成
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//一个工具类用于生成随机的Id
//每一个物体的Id独特且唯一,用于区分物体
//用静态来修饰,静态类不能创建实例,只能用静态的方法
public static class Id
{
static ulong ss = 0; //静态全局的变量
static public ulong Generate() //ID不能为负数 32/16位
{
ulong id=0;
//直接Random会重,带个时间,用相对时间的时刻来随机,保证相对独特
TimeSpan d= DateTime.Now-new DateTime(2000,1,1);
//Now一直增加,每次调用随出来的数是唯一的,有精度的问题,在一个很短的时间那 1ms/2ms
//有可能差距很小,精度不够可能使时间相同
//规避一下
ulong s = (ulong)d.TotalMilliseconds % 0xFFFFFFFFFF; //double的类型精确到毫秒
++ss; //最终是两个数运算一块
//相加和相乘也会重,用位运算去合 long是64位数,
//40 24,把这两个数整体放在一个地方,
//[0,39]存一个数 [40,63]存一个数
if (ss >= 0xFFFFFF) //与24为判断大小,一个16位置是4个2进制位数
{
ss = 0; //让它从0开始
}
id =(ss)|(s<<40);
return id;
}
}
封装
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* 封装:将一个特定功能的代码将其封装到一个方法或者函数中
* 达到代码的复用,只写一次可以多次用相同的,可读性
* https://www.cnblogs.com/xinaixia/p/5768148.html
* static 用法
*/
public class Test2: MonoBehaviour
{
[ContextMenu("2")]
void Start()
{
int[] arrary = new int[5] { 1, 2, 3, 4, 5 };
int num = 1;
int[] newArray = ArrayTools.ReamoveAt(arrary, num);
arrary = newArray;
//封装后一眼就能看懂
//是否足够通用?如果这个抽象没人用就浪费了
//要有包容性,但又不能过于复杂,
//对于容器类可以按类型来抽象
float[] array2=new float[5] {1,2,3, 4,5};
//所以应该把上面改了改成模板函数
}
/*
private static T[] ReamoveAt<T>(T[] arrary, int num)
{
if (num >= arrary.Length || num < 0) num = arrary.Length - 1;
T[] newArray = new T[arrary.Length - 1];
if (num != 0) Array.Copy(arrary, newArray, num);
if (num != arrary.Length) Array.Copy(arrary, num + 1, newArray, num, newArray.Length - num);
return newArray;
}
//对于这段代码还可以封装到专门的类里
*/
}
扩展类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using OpWorld.Core;
/*使用这种方法来扩展
* 1.容器的增加还有删除,自带方法不够全面
* 2.构造还有复制,想把过程隐藏封装到方法里就要自己扩展
* 3.转换 容器,类型,单位 ,角度或者弧度,字符串之间的转换,打印类就是转换成字符串
*/
public class Test3 : MonoBehaviour
{
/* public void RotateOn2(Transform transform,float angle)
{
Vector3 euler = transform.rotation.eulerAngles;
euler.z += angle;
transform.rotation=Quaternion.Euler(euler);
}
*/
/*
* 不想把代码放在类里想要直接放在transform上
* tranform是unity自己的类,他的代码没法改
* 要扩展,只能通过另外的手段,不修改源码的情况扩展
* 可以写在Extensions
*/
[ContextMenu("3")]
void Start()
{
Transform myTransform=GetComponent<Transform>();
myTransform.RotateOnZ(90f); //跟定义了类的内部方法一样
//无缝连接,通过外部改代码来增肌,比在全局写好,面向过程的编程
//以后要加方法就可以找一个全局的静态类放进去
}
// Update is called once per frame
void Update()
{
}
}