记录一些东西

插件
Unity插件

热更

huatuo
GitHub链接

InjectFix
GitHub链接

unity 应用被切出去时监听
true 在unity应用, false 切出去了

MonoBehaviour.OnApplicationFocus(bool)

GetEnumerator
是返回实例的枚举数。换句话说就是返回集的中所有元素一个一个列出来。
我们可以通过MoveNext()得到集合中的所有元素。

Dictionary<int,string>.Enumerator enumerator = dictionary.GetEnumerator();
while  (enumerator.MoveNext())
{
	int  key  =  enumerator.Current.Key;
	string  value  =  enumerator.Current.Value;
}

时间:

System.DateTime.Now.ToLongTimeString()

电量:

SystemInfo.batteryLevel.ToString()
SystemInfo.batteryLevel.ToString()

网络:

string network = string.Empty;
if (Application.internetReachability == NetworkReachability.NotReachable)
    network = "当前网络:不可用";
else if (Application.internetReachability == NetworkReachability.ReachableViaCarrierDataNetwork)
    network = "当前网络:3G/4G";
else if (Application.internetReachability == NetworkReachability.ReachableViaLocalAreaNetwork)
    network = "当前网络 : WIFI";

正则表达式使用

string json;
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"(?i)\\[uU]([0-9a-f]{4})");
string str = reg.Replace(json, (m) => { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });

防止息屏

 Screen.sleepTimeout = SleepTimeout.NeverSleep;

/禁止旋转到竖屏

Screen.autorotateToPortrait = false;

// 性能优化

```csharp
//渲染帧率
 Application.targetFrameRate = 30;
//在一些静态UI的时候把OnDemandRendering.renderFrameInterval设置为3,表示渲染频率降为1/3。假设正常是30fps,那么渲染帧率就是10fps。
OnDemandRendering.renderFrameInterval = 3;

组件重写

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEditor;
using UnityEditor.UI;
public class MyDropdown : Dropdown
{
//显示在unity的Inspector面板上
    [SerializeField]
    private Canvas m_ParentCanvas;
}

[CustomEditor(typeof(MyDropdown), true)]
[CanEditMultipleObjects]
public class MyDropdownEditor : DropdownEditor
{
    private SerializedProperty m_ParentCanvas;

    protected override void OnEnable()
    {
        base.OnEnable();
        m_ParentCanvas = serializedObject.FindProperty("m_ParentCanvas");
    }

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        EditorGUILayout.Space();//空行
        serializedObject.Update();
        EditorGUILayout.PropertyField(m_ParentCanvas);//显示我们创建的属性
        serializedObject.ApplyModifiedProperties();
    }
}

保存相机RenderTexture

    private void _SaveRenderTexture(RenderTexture rt)
    {
        RenderTexture active = RenderTexture.active;
        RenderTexture.active = rt;
        Texture2D png = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, false);
        png.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
        png.Apply();
        RenderTexture.active = active;
        byte[] bytes = png.EncodeToPNG();
        string path = string.Format("123.png");
        FileStream fs = File.Open(path, FileMode.Create);
        BinaryWriter writer = new BinaryWriter(fs);
        writer.Write(bytes);
        writer.Flush();
        writer.Close();
        fs.Close();
        Destroy(png);
        png = null;
        Debug.Log("保存成功!" + path);
    }

保存RenderTexture 为pgn图片

		RenderTexture active = RenderTexture.active;
        RenderTexture.active = camera.targetTexture;
        //Tet = new Texture2D(camera.targetTexture.width, camera.targetTexture.height, TextureFormat.RGBA32, false);
        Tet = new Texture2D(600, 600, TextureFormat.RGBA32, false);

        Tet.ReadPixels(new Rect(0, 0, camera.targetTexture.width, camera.targetTexture.height), 0, 0);
        Tet.Apply();
        byte[] bytes = Tet.EncodeToPNG();

        if (Application.platform == RuntimePlatform.Android)
        {
            destination = "/sdcard/DCIM/monkey";
            if (!Directory.Exists(destination))
            {
                Directory.CreateDirectory(destination);
            }
        }
        else
            destination = "Assets/Image/";
        File.WriteAllBytes(destination + "/" + name + ".png", bytes);

保存本地 转json

private void SaveJson()
    {
        string strPath;
        if (Application.platform == RuntimePlatform.Android)
            strPath = Application.persistentDataPath + "/dic.json";
        else
            strPath = "Assets/Json" + "/dic.json";
        string values = JsonUtility.ToJson(new Serialization<string>(dic));
        File.WriteAllText(strPath, values);
    }

public List<string> LoadJson()
    {
        string strPath;
        if (Application.platform == RuntimePlatform.Android)
            strPath = Application.persistentDataPath + "/dic.json";
        else
            strPath = "Assets/Json" + "/dic.json";
        if (File.Exists(strPath))
        {
            var content = File.ReadAllText(strPath);
            var Data = JsonUtility.FromJson<Serialization<string>>(content).ToList(); ;
            return Data;
        }
        else
        {
            Debug.LogError("Save file not found in  " + strPath);
            return new List<string>();
        }
    }

[Serializable]
public class Serialization<T>
{
    [SerializeField]
    List<T> target;
    public List<T> ToList() { return target; }

    public Serialization(List<T> target)
    {
        this.target = target;
    }
}

// Dictionary<TKey, TValue>
[Serializable]
public class Serialization<TKey, TValue> : ISerializationCallbackReceiver
{
    [SerializeField]
    List<TKey> keys;
    [SerializeField]
    List<TValue> values;

    Dictionary<TKey, TValue> target;
    public Dictionary<TKey, TValue> ToDictionary() { return target; }

    public Serialization(Dictionary<TKey, TValue> target)
    {
        this.target = target;
    }

    public void OnBeforeSerialize()
    {
        keys = new List<TKey>(target.Keys);
        values = new List<TValue>(target.Values);
    }

    public void OnAfterDeserialize()
    {
        var count = Math.Min(keys.Count, values.Count);
        target = new Dictionary<TKey, TValue>(count);
        for (var i = 0; i < count; ++i)
        {
            target.Add(keys[i], values[i]);
        }
    }
}

旋转

        //Input .GetAxis ("Mouse X"); 得到鼠标在水平方向的滑动
        //Input .GetAxis ("Mouse Y");得到鼠标在垂直方向的滑动
        if (Input.GetMouseButtonDown(0))
        {//0代表左键1代表右键2代表中键
            if (go.activeInHierarchy)
                go.SetActive(false);
            if (EventSystem.current.currentSelectedGameObject == null)
                isRotating = true;
        }
        if (Input.GetMouseButtonUp(0))
        {
            isRotating = false;
        }
        if (isRotating)
        {
            transform.RotateAround(transform.position, Vector3.up, - rotateSpeed * Input.GetAxis("Mouse X"));
        }

委托

public class FriendItem : MonoBehaviour
{
    //public FriendShipList friendList;
    public delegate void ActionFriendItem(string id);  定义委托
    private ActionFriendItem act;  定义事件

	给事件复制
    public void SetFriendItem( ActionFriendItem action)
    {
        act = action;
    }

	调用定义的委托中的事件
    private void OnThis()
    {
        act(playerId);
    }
}
public class MUIFriend : MUIBase
{
    private RepeatedField<FriendShipList> friendlist;
    private List<GameObject> listgoFriendItem = new List<GameObject>();
    private string friendPlayerId;

    private void SetFriend()
    {

        FriendItem go = listgoFriendItem[0].GetComponent<FriendItem>();
        使用定义的委托,传需要使用的方法
        go.SetFriendItem(friendlist[0], (string id) =>
        {
            friendPlayerId = id;
        });
    }
}

Unity 调原生

 //Android
 private AndroidJavaObject jo;
    private void Start()
    {
    //固定写法
        AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");  //创建安卓类
        jo = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");    //获取安卓对象
        btn.onClick.AddListener(OnBtn);
    }

    public void OnBtn()
    {
        jo.Call("OnBtn");
    }
 //ios

```csharp
    [DllImport("__Internal")]
    private static extern void _BuglyInit(string appId, bool debug, int level);

untiy协程

yield return null; // 下一帧再执行后续代码
yield return 6;//(任意数字) 下一帧再执行后续代码
yield break; //直接结束该协程的后续操作
yield return asyncOperation;//等异步操作结束后再执行后续代码
yield return StartCoroution(/*某个协程*/);//等待某个协程执行完毕后再执行后续代码
yield return WWW();//等待WWW操作完成后再执行后续代码
yield return new WaitForEndOfFrame();//等待帧结束,等待直到所有的摄像机和GUI被渲染完成后,在该帧显示在屏幕之前执行
yield return new WaitForSeconds(0.3f);//等待0.3秒,一段指定的时间延迟之后继续执行,在所有的Update函数完成调用的那一帧之后(这里的时间会受到Time.timeScale的影响);
yield return new WaitForSecondsRealtime(0.3f);//等待0.3秒,一段指定的时间延迟之后继续执行,在所有的Update函数完成调用的那一帧之后(这里的时间不受到Time.timeScale的影响);
yield return WaitForFixedUpdate();//等待下一次FixedUpdate开始时再执行后续代码
yield return new WaitUntil()//将协同执行直到 当输入的参数(或者委托)为true的时候....如:yield return new WaitUntil(() => frame >= 10);
yield return new WaitWhile()//将协同执行直到 当输入的参数(或者委托)为false的时候.... 如:yield return new WaitWhile(() => frame < 10);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值