Unity前端开发实战笔记(持续更新.....)

activeInHierarchy 和 activeSelf 区别

activeInHierarchy:是否在场景中显示

activeSelf:是否在Inspector面板被勾选(可能有在场景中不显示的情况,因为可能父节点被隐藏了,但是activeSelf仍然可以为true)

Transform.Find的坑

在设置对象的名称时候可能存在末尾空格的情况例如"myName ",这种情况如果通过Transform.Find("myName")是查找不到的,所以要注意这种情况

如何获取rotation 对应地角度值

Text组件的坑

如果输入内容后,Text组件显示不了内容,可能是Font Size设置过大

1、可以通过调小Size或者拉大Text宽高

2、可以添加Content Size Fitter组件,根据内容大小自动适配Text组件的宽或高。

字典静态声明

static string[] sExtensionNames = new []
{
    "...",
    "消息系统 (MessageSystem)",
    "战斗系统 (FightSystem)",
    "掉落系统 (DropSystem)",
    "机关发射器 (EmitterSystem)",
    "机关接收器 (AcceptorSystem)",
};

static Dictionary<string,string> ExtensionDic = new Dictionary<string, string>()
{
    {"...","..."},
    { "MessageSystem","消息系统 (MessageSystem)"},
    { "FightSystem","战斗系统 (FightSystem)"},
    { "DropSystem","掉落系统 (ThrowSystem)"},
    { "EmitterSystem","机关发射器 (EmitterSystem)"},
    { "AcceptorSystem","机关接收器 (AcceptorSystem)"},
};

判断ScrollView是否上滑还是下滑

var yValue = scrollRect.velocity.y;
if (yValue > 0)
{
    Debug.Log("下滑");
}
else
{
    Debug.Log("上滑");
}

设置英文单词首字母大写

string str = "hello";
var result = str.Substring(0, 1).ToUpper() + str.Substring(1);

如何清理Unity占用的C盘空间

  1. 删除C盘用户文件夹下AppData\Roaming\Unity\Asset Store-5.x的内容,或者将其转移到其他文件夹,下次使用时手动拷贝到项目Asset文件夹下。从资源商店下载的所有文件夹均存储在这里,Unity目前尚未提供修改资源商店存储路径的入口。
  2. 删除C盘用户文件夹下AppData\Local\Unity\cache的子文件夹npm和packages的内容。这两个文件夹储存的是从package manager导入的各种插件,下次运行带插件项目时,会在该文件夹下自动重新生成最新版插件资源。
  3. 打开Unity,Edit>Preference,在GI Cache项下清除缓存,也可更改GI Cache文件夹位置。

UI播放视频

(1)创建一个Raw Image

(2)创建一个Render Texture

(3)给Raw Image挂载一个Video Player组件

Unity中实现定时器

Time.deltaTime

public float timer = 0f; 

private void Update()
{
    timer += Time.deltaTime;
    if (timer >= 2)
    {
        DoSomething();
        timer = 0f; // 定时2秒
    }
}

void DoSomething()
{
    Debug.Log("每2秒执行一次");
}

 使用延迟调用函数

void Start()
{
    //0秒后,每2秒执行一次doSomething
    InvokeRepeating("DoSomething", 0, 2);
}

void DoSomething()
{
    Debug.Log("每2秒执行一次");
}

 使用协程

void Start()
{
    //每2秒执行一次doSomething
    StartCoroutine(UpdateTimer(2f, DoSomething));
}

void DoSomething()
{
    Debug.Log("每2秒执行一次");
}

IEnumerator UpdateTimer(float timer,Action callBack)
{
    var wait = new WaitForSeconds(timer);
    while (true)
    {
        yield return wait;
        callBack();
    }
}

Mask 根据像素所在范围进行裁剪

Rect Mask 2D 进行矩形裁剪

还可进行边缘虚化

宏定义使用

#if UNITY_STANDALONE_WIN

  Debug.Log("Standalone Windows");

#endif


#if UNITY_EDITOR_WIN ||UNITY_STANDALONE
        
#elif UNITY_ANDROID
        
#else

#endif


#if UNITY_EDITOR
#endif
        
#if UNITY_IPHONE
#endif
        
#if UNITY_IOS
#endif
        
#if UNITY_IPHONE
#endif
        
#if UNITY_ANDROID
#endif
        
#if UNITY_WEBGL
#endif

Rider常用快捷键

功能

快捷键

注释

Ctrl+/

跳转到代码定义

Ctrl+B

选中当前行

鼠标三击

跳转到指定行

Ctrl+G

自动整理代码格式

Ctrl+Alt+L

页面切换

Alt+←,→

(断点调试),运行到下一行

F8

(断点调试),退出断点,恢复程序

F9

重写方法快捷键

Ctrl + O

当前脚本查找

Ctrl+F

全局查找

Ctrl+Shift+F

返回上一步

Ctrl+Y

全部展开

Ctrl+Shift++

全部折叠

Ctrl+Shift+-

返回至上次浏览位置

Ctrl+Alt+<-/->

按钮点击动效

需要借助Dotween插件

using UnityEngine;
using UnityEngine.EventSystems;
using DG.Tweening;
 
public class BtnClickEffect : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public void OnPointerDown(PointerEventData eventData)
    {
        transform.DOScale(Vector3.one * 0.85f, 0.2f).SetEase(Ease.OutCubic);
    }
 
    public void OnPointerUp(PointerEventData eventData)
    {
        transform.DOScale(Vector3.one, 0.3f);
    }
 
    private void OnDisable()
    {
        transform.DOKill();
    }
}

判断概率事件是否成功

Lua:

function  IsSuccess(ratio)
    local commitPercent = ratio;--成功概率
    local criticalValue = commitPercent*10000; --成功临界值
    math.randomseed( tonumber(tostring(os.time()):reverse():sub(1,6)))
    local randomNum = math.random(1,10000);
    if randomNum > criticalValue then
        print("失败",randomNum)
    else
        print("成功",randomNum)
    end
end 

Unity实现单例类

using UnityEngine;

/// <summary>
/// 单例
/// </summary>
/// <typeparam name="T"></typeparam>
public class MonoSingleton<T> : MonoBehaviour
  where T : Component
{
    private static T _instance;

    public static T Instance => _instance;

    public virtual void Awake()
    {
        if (_instance == null)
        {
            _instance = this as T;
        }
    }
}

颜色码和Color类型互转

//颜色码转Color
bool isSuccess = ColorUtility.TryParseHtmlString("#FECEE1", out Color result);
        
//Color转颜色码
string hex = ColorUtility.ToHtmlStringRGB(new Color(0.4f, 0.7f, 0.9f));

加载场景

    
    private Slider loadingSlider;
    private TMP_Text loadText;
    public void LoadMultiplay()
    {
       
        StartCoroutine(LoadAsync(1));
    }

    IEnumerator LoadAsync(int sceneIndex)
    {
        AsyncOperation operation = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(sceneIndex);
        while (!operation.isDone)
        {
            loadingSlider.value = operation.progress;
            int loadingValue = Convert.ToInt32(loadingSlider.value);
            loadText.text = $"{loadingValue * 100}%";
            yield return null;
        }
    }

挂载布局组件后获取尺寸问题

通常获取UI的宽和高,一般使用GetComponent<RectTransform>().rect.height或GetComponent<RectTransform>().rect.width,但是使用Content Size Fitter布局后会获取不到对应的值(获取为0),此时强制刷新一下布局再获取即可。

LayoutRebuilder.ForceRebuildLayoutImmediate(rectTransform)

刷新完再使用GetComponent<RectTransform>().rect获取。

判断3D角色爬坡或下坡

void Update()
{
    this.transform.Translate(new Vector3(0, 0, 2f) * Time.deltaTime * speed);
    float h = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
    float v = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;

    if (OnSlope())
    {
        transform.forward = Vector3.ProjectOnPlane(transform.forward, hitNormal);
        Debug.Log("我在斜面上");
    }

    OnSlope();
    transform.Translate(h, 0, v);
}


/// <summary>
/// 射线检测是否在斜面进行角色爬坡或下坡
/// </summary>
/// <returns></returns>
private bool OnSlope()
{
    Ray ray = new Ray(groundCheck.position, Vector3.down);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit, rayLength))
    {
        hitNormal = hit.normal;
        float slopeAngle = Vector3.Angle(hit.normal, Vector3.up);
        if (slopeAngle < maxSlopeAngle)
        {
            Debug.Log(slopeAngle);
            return true;
        }
    }

    return false;
}

Visual Studio快捷键

返回上一步Ctrl+Y

将代码注释:ctrl+k+c

快速取消注释:ctrl+k+u

裁剪粘贴 :Ctrl+x ctrl+v

对齐代码:ctrl+k+F

统一更改同一变量名:Ctrl+H

打开分析器(Profiler)Ctrl+7

触摸屏幕手指控制物体移动

public class TouchTest : MonoBehaviour
{
    public Transform currTouchObj;
    private Camera mainCamera;
    private void Awake()
    {
        mainCamera = Camera.main;
    }

    public void CtrlTouchObjMove()
    {
 		if (Input.touchCount == 1)
        {
            Touch firstTouch = Input.GetTouch(0);
            if (firstTouch.phase == TouchPhase.Began)
            {
                Ray ray = mainCamera.ScreenPointToRay(firstTouch.position);
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit))
                {
                		//获取当前触摸到的物体
                        currTouchObj = hit.collider.transform;
                }
            }

            if (Input.GetTouch(0).phase == TouchPhase.Moved)
            {     
                if (currTouchObj)
                {
                    Vector3 touchDeltaPos = Input.GetTouch(0).deltaPosition;
                    currTouchObj.Translate(touchDeltaPos.x * touchObjMoveSpeed, touchDeltaPos.y * touchObjMoveSpeed, 0, Space.World);
                }
            }
	}
}

交换数值优化

//优化前
var temp = list[value];
list[value] = list[index];
list[index] = temp;

//优化后
(list[value], list[index]) = (list[index], list[value]);

 预制体操作恢复历史记录

有时候在Git工具中把某个预制体覆盖了文件改动,把界面的一些改动都删除了。可以通过

Editor->Undo History来查看并恢复

 Unity 复制内容到剪贴板

//第一种
TextEditor te = new TextEditor();
te.text = "添加英雄招募券";
te.SelectAll();
te.Copy();

//第二种
GUIUtility.systemCopyBuffer = "添加幸存者招募券";

猜你喜欢

转载自blog.csdn.net/qq_44809934/article/details/145616744