[some notes]

**OnGUI**
script driver, can be used for mobile terminal debugging

Text
Rich text - can be compared to html tags
Horizontal/vertical direction can overflow
Raycast castTarget Raycast target, can be used to indicate whether to respond to rays (I don't understand it for now)
Best fit can make the font adaptive to the current object (border )

Image
Source Image Select Load Resource
Image Type Optional → Slicing: The four corners will not be deformed (the image needs to be divided into nine squares first)
Filling: It will be deformed and can be used to display incomplete images (can be used for skill cooling)
Optional Keep the aspect ratio, whether the mask disappears clockwise or counterclockwise.
Tiling: No deformation at all, repeat the picture and spread the current picture
RawImage
texture format, can bind all types of
UV rectangles (Rect)

After creating an img file, click here

and hold down alt to select the lower right corner, (automatically fill the entire canvas)

Button
creates a button animation that binds an event
to jump to a scene statement
SceneManager
insert image description here

  SceneManager.LoadScene("场景名称",);

event interface

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class test : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    
    
    void Start()
    {
    
       
    }

    void Update()
    {
    
    
    }
    public void OnPointerDown(PointerEventData eventData)
    {
    
    
        Debug.Log("鼠标按下");
        // Doll_anima.SetBool("close", false);
    }
    public void OnPointerUp(PointerEventData eventData)
    {
    
    
        Debug.Log("鼠标抬起");
        //Doll_anima.SetBool("close", true);
    }
}

Unity animation
When you click creat to create an animation, the system automatically creates an animation controller (state machine) to
open the animation, where Sample represents sampling, which means that the animation will play at a few frames per second
and then open the controller
insert image description here

When right-clicking on an animation: Set as layer Default state (set as the default animation, so the controller will start from an idle state)
Any State is a shortcut to add the same outward state transition to all states in the machine

Passing values ​​between scripts
It is more common to use SendMessage to pass parameters on the Internet, but the writing is not very clear.

SendMessage is a function that comes with GameObject, which can pass similar parameters to similar components under GameObject. The script is used as a component, and parameters can also be passed.

Because it is a function of GameObject, it is necessary to define the Instance of GameObject first, or use GameObject.Find("instance name") to find the corresponding instance. "DeviceStatus" in the figure below is an instance name.

GameObject.Find("DeviceStatus").GetComponent<IP>().SendMessage("setIP",IPAdd);

Suppose you want to pass parameters to this game instance object in a triggered script, assuming that the script name under the DeviceStatus object is "IP.cs", then the script name "IP" should be in the angle brackets after GetComponent, and then Then SendMessage("function name", value)

The idea of ​​storing game object data
is probably to create an empty game object, store all the parameters that need to be passed in the scene into the game object, and prohibit the destruction of the game object when switching scenes.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameSave : MonoBehaviour
{
    
    
    //设定当前图片链接
    private string currentUrl;
    private string currentName;
    private string currentDate;

    private void Awake()
    {
    
    
        DontDestroyOnLoad(transform.gameObject);//不摧毁当前游戏对象
    }

    private void saveurl(string url)
    {
    
    
        currentUrl = url; //设置保存当前图片对象
    }
    private void savename(string name)
    {
    
    
        currentName = name; //设置保存当前名字对象
    }
    private void savedate(string date)
    {
    
    
        currentDate = date; //设置保存当前日期对象
    }
}

Switch scene monitoring when the mouse is clicked

public class Cilck : MonoBehaviour,IPointerClickHandler
{
    
     

    public void OnPointerClick(PointerEventData eventData)
    {
    
    
        SceneManager.LoadScene("branch");//level1为我们要切换到的场景
        Debug.Log("EventSystem.current.currentSelectedGameObject.url");
    }


}

Set the animation state transition value statement

   public void OnPointerEnter(PointerEventData eventData)
    {
    
    
         Doll_anima.SetBool("wake", true);
      
    }
    public void OnPointerExit(PointerEventData eventData)
    {
    
    
        Doll_anima.SetBool("wake", false);
    }

A network address image loading code
Unity uses UnityWebRequest for network and local image loading

///LoadImageMgr.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using UnityEngine.Networking;
public class LoadImageMgr
{
    
    
    /// <summary>
    /// download from web or hard disk
    /// </summary>
    /// <param name="url"></param>
    /// <param name="loadEnd">callback</param>
    /// <returns></returns>
    public IEnumerator LoadImage(string url, Action<Texture2D> loadEnd)
    {
    
    
        Texture2D texture = null;
        //先从内存加载
        if (imageDic.TryGetValue(url,out texture))
        {
    
    
            loadEnd.Invoke(texture);
            yield break;
        }
        string savePath = GetLocalPath();
        string filePath = string.Format("file://{0}/{1}.png", savePath, UnityUtil.MD5Encrypt(url));
        //from hard disk
        bool hasLoad = false;
        if (Directory.Exists(filePath))
            yield return DownloadImage(filePath, (state, localTexture) =>
            {
    
     
                hasLoad = state;
                if (state)
                {
    
    
                    loadEnd.Invoke(localTexture);
                    if (!imageDic.ContainsKey(url))
                        imageDic.Add(url, localTexture);
                }
            });
        if (hasLoad) yield break; //loaded
        //from web
        yield return DownloadImage(url, (state, downloadTexture) =>
        {
    
    
            hasLoad = state;
            if (state)
            {
    
    
                loadEnd.Invoke(downloadTexture);
                if (!imageDic.ContainsKey(url))
                    imageDic.Add(url, downloadTexture);
                Save2LocalPath(url, downloadTexture);
            }
        });
    }
    public IEnumerator DownloadImage(string url, Action<bool, Texture2D> downloadEnd)
    {
    
    
        using (UnityWebRequest request = new UnityWebRequest(url))
        {
    
    
            DownloadHandlerTexture downloadHandlerTexture = new DownloadHandlerTexture(true);
            request.downloadHandler = downloadHandlerTexture;
            yield return request.Send();
            if (string.IsNullOrEmpty(request.error))
            {
    
    
                Texture2D localTexture = downloadHandlerTexture.texture;
                downloadEnd.Invoke(true, localTexture);
            }
            else
            {
    
    
                downloadEnd.Invoke(false, null);
                Debug.Log(request.error);
            }
        }
    }
    /// <summary>
    /// save the picture
    /// </summary>
    /// <param name="url"></param>
    /// <param name="texture"></param>
    private void Save2LocalPath(string url, Texture2D texture)
    {
    
    
        byte[] bytes = texture.EncodeToPNG();
        string savePath = GetLocalPath();
        try
        {
    
    
            File.WriteAllBytes( string.Format("{0}/{1}.png", savePath , UnityUtil.MD5Encrypt(url)), bytes);
        }
        catch(Exception ex)
        {
    
    
            Debug.LogError(ex.ToString());
        }
    }
    /// <summary>
    /// get which path will save
    /// </summary>
    /// <returns></returns>
    private string GetLocalPath()
    {
    
    
        string savePath = Application.persistentDataPath + "/pics";
#if UNITY_EDITOR
        savePath = Application.dataPath + "/pics";
#endif
        if (!Directory.Exists(savePath))
        {
    
    
            Directory.CreateDirectory(savePath);
        }
        return savePath;
    }
    private Dictionary<string, Texture2D> imageDic = new Dictionary<string, Texture2D>();
    public static LoadImageMgr instance {
    
     get; private set; } = new LoadImageMgr();
}

Mesh grid
official description
Unity draws graphics through Mesh grid: triangle & cube & cylinder

draw a triangle

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Cube : MonoBehaviour
{
    
    
    Mesh mesh;
    Vector3[] vectices;
    int[] cube;

    private void Awake()
    {
    
    
        mesh = GetComponent<MeshFilter>().mesh;
    }
    private void Start()
    {
    
    
        CreateMeshData();
        Draw();

    }

    void CreateMeshData()
    {
    
    
        vectices = new Vector3[]
        {
    
    
            new Vector3(0,0,0),
            new Vector3(1,0,0),
            new Vector3(0,1,0),
        };
        cube = new int[]{
    
    
            0,1,2
        };
    }

    private void Draw()
    {
    
    
        mesh.Clear();
        mesh.vertices = vectices;
        mesh.triangles = cube;
        mesh.RecalculateNormals();//自动计算法线

    }

}

PS.
1. Watch the video and see the point of RaycastTarget, and see a post that says this:

Friends who have seen the UGUI source code must know that UI events will be triggered in the EventSystem in the Update Process. UGUI will traverse all the UIs in the screen whose RaycastTarget is true, and then emit lines, and sort to find the UI that the player triggers first, and throw an event to the logic layer to respond.

Many people in the team are developing the game interface, and they are often copied and pasted. For example, the last picture needs to respond to RaycastTarget, and then copied after ctrl+d also has this attribute. It is likely that the newly copied picture does not need it. Responsive, the developer did not uncheck it, and this is a problem.

Therefore, if RaycastTarget is checked too much, the efficiency will inevitably be low. .

Original post: Yusong MOMO UGUI effectively solves the trouble of RaycastTarget checking too much (23)

2. Solve the problem of slow opening of API documents on the official website of UNITY
The solution to the slow opening speed of unity3d local api

3. Some points that need attention
Do not use Find, FindwithTag... etc.
You can directly

4. Get the path name of the path

Name = path.Substring(path.LastIndexOf('/') + 1);

Find the first character of the last last /

2022/3/2 blood volume and blood bar display script, lookat()

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 控制怪物血量条的展示和跟随
/// </summary>
    public class Healthbar_UI : MonoBehaviour
    {
    
    

     
        public GameObject HealthUIPrefab;//血条的预制体 
        public GameObject barpoint;//怪物的血条位置

        Image healthSlider;//血量的滑动条
        Transform UIbar;//血条位置
        Transform cam;//摄像机位置

    public bool alwaysVisible = true;//是否可见
        public float visibleTime;//可见时长

        private void OnEnable()
        {
    
    
            cam = Camera.main.transform;//挂载摄像机
             UIbar = Instantiate(HealthUIPrefab,this.transform, barpoint).transform;
             healthSlider = UIbar.GetChild(1).GetComponent<Image>();//获取绿条
             UIbar.gameObject.SetActive(alwaysVisible);//设置是否长久可见
        }


         //血条跟随敌人
        private void LateUpdate()
        {
    
    
            if (UIbar != null)
            {
    
    
                UIbar.position = barpoint.transform.position;
                UIbar.forward = -cam.forward;
            }
        }
        /// <summary>
        /// 控制血量展示
        /// </summary>
        /// <param name="currentHealth">当前的生命值</param>
        /// <param name="maxHealth">最大血量</param>
        public void UpdateHralthBar(float currentHealth,float maxHealth)
        {
    
    
            //当血量归0时,摧毁血条
            if (currentHealth <= 0)
                Destroy(UIbar.gameObject);


            UIbar.gameObject.SetActive(true);

            //控制滑条显示的百分比(强制转换为int类型)
            float sliderPercent = currentHealth / maxHealth;
            healthSlider.fillAmount = sliderPercent;
        }
    }

look at() can achieve almost the same effect. This method is used in Update() to indicate that the object is always facing the camera

LateUpdate(), this function is a function inside Unity, which is called immediately after Update()

 Invoke(String fun_name, float time)

Delay calling a certain function fun_name is the function name, and time is the number of seconds to delay calling.

Use of the DateTime class

Guess you like

Origin blog.csdn.net/weixin_42818410/article/details/122866716