Unity3D

Unity 常用代码段和知识点

页面
字体
小树 · 11月13日 · 2019年 ·

0x1. Instantiate

using UnityEngine;
using System.Collections;

public class UsingInstantiate : MonoBehaviour
{
    public Rigidbody rocketPrefab;
    public Transform barrelEnd;
    
    void Update ()
    {
        if(Input.GetButtonDown("Fire1"))
        {
            Rigidbody rocketInstance;
            rocketInstance = Instantiate(rocketPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
            rocketInstance.AddForce(barrelEnd.forward * 5000);
        }
    }
}

0x2. Invoke

InvokeScript

using UnityEngine;
using System.Collections;

public class InvokeScript : MonoBehaviour 
{
    public GameObject target;
    
    void Start()
    {
        Invoke ("SpawnObject", 2);
    }
    
    void SpawnObject()
    {
        Instantiate(target, new Vector3(0, 2, 0), Quaternion.identity);
    }
}

InvokeRepeating

using UnityEngine;
using System.Collections;

public class InvokeRepeating : MonoBehaviour 
{
    public GameObject target;
    
    void Start()
    {
        InvokeRepeating("SpawnObject", 2, 1);
    }
    
    void SpawnObject()
    {
        float x = Random.Range(-2.0f, 2.0f);
        float z = Random.Range(-2.0f, 2.0f);
        Instantiate(target, new Vector3(x, 2, z), Quaternion.identity);
    }
}

0x3. Load / Save

https://answers.unity.com/questions/8480/how-to-scrip-a-saveload-game-option.html

0x4. 2D light 2D照明

https://www.youtube.com/watch?v=nkgGyO9VG54

0x5. CharacterController.collisionFlags

    private void OnControllerColliderHit(ControllerColliderHit hit)
    {
        //获取CharacterController发生碰撞的面flags
        if(characterController.collisionFlags == CollisionFlags.Sides)
        {
            Debug.DrawRay(transform.position, hit.normal,Color.red,2f);
        }
    }

0x6. 自定义isGrounded

    //自定义的是否接地函数
    private bool isCharacterControllerGrounded()
    {
        Vector3 leftRayStart, rightRayStart;
        leftRayStart = characterController.bounds.center; //CharacterController的中心点
        rightRayStart = characterController.bounds.center;
        leftRayStart.x -= characterController.bounds.extents.x; // -= 半径:球体最左侧
        rightRayStart.x += characterController.bounds.extents.x; // += 半径:球体最右侧

        Debug.DrawRay(leftRayStart, Vector3.down, Color.red);
        Debug.DrawRay(characterController.bounds.center, Vector3.down, Color.green);
        Debug.DrawRay(rightRayStart, Vector3.down, Color.yellow);

        //如果Raycast射线碰撞,return true ,0.2为缓冲区,会产生间隙,处理间隙在下方
        if (Physics.Raycast(leftRayStart, Vector3.down, characterController.height / 2 + 0.2f))
            return true;

        if (Physics.Raycast(rightRayStart, Vector3.down, characterController.height / 2 + 0.2f))
            return true;



        return false;
    }

0x7. NavMesh 自动寻路

https://github.com/Unity-Technologies/NavMeshComponents#documentation-draft

https://www.youtube.com/watch?v=CHV1ymlw-P8

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

public class PlayerController : MonoBehaviour
{
    public Camera cam;
    public NavMeshAgent agent;

    //墙体添加 NavMeshModifier 组件,override area为not walkable
    //Player添加NavMeshAgent组件,设置好Agent的参数
    //NavMesh添加 NavMeshSurface 组件,bake生成

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ScreenPointToRay(Input.mousePosition); //鼠标屏幕坐标转世界坐标
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                //Move our agent
                agent.SetDestination(hit.point);
            }
        }    
    }
}

0x8. PhotoShop像素画

https://www.youtube.com/watch?v=rLdA4Amea7Y

0x9. 移动端触摸GetTouch

//触摸点数量
if(Input.touchCount>0){
    Touch touch = Input.getTouch(0);
    Vectory3 p = Camera.main.ScreenToWorldPoint(touch.position);
    // p is The Position U Touch
} 
//或使用 asset store的 Joystick Pack 触控板

0x10. 2D Platformer Character Controller

https://learn.unity.com/tutorial/live-session-2d-platformer-character-controller

This is all great stuff, but that character controller tutorial is a bit crap. This one is much better: https://www.youtube.com/watch?v=MbWK8bCAU2w But still has issues with slopes in some cases, and the code needs cleaning up. Loads of controllers available on the asset store as well, I particularly like the Kinematic 2D controller.

0x11. parallax scrolling 视差滚动

正交摄像机下实现视差滚动

https://www.youtube.com/watch?v=2MImqNvgrNg

https://answers.unity.com/questions/551808/parallax-scrolling-using-orthographic-camera.html

 [ExecuteInEditMode]
 public class ParallaxBackground : MonoBehaviour
 {
   public ParallaxCamera parallaxCamera;
   List<ParallaxLayer> parallaxLayers = new List<ParallaxLayer>();
  
   void Start()
   {
       if (parallaxCamera == null)
         parallaxCamera = Camera.main.GetComponent<ParallaxCamera>();
       if (parallaxCamera != null)
         parallaxCamera.onCameraTranslate += Move;
       SetLayers();
   }
  
   void SetLayers()
   {
       parallaxLayers.Clear();
       for (int i = 0; i < transform.childCount; i++)
       {
           ParallaxLayer layer = transform.GetChild(i).GetComponent<ParallaxLayer>();
  
           if (layer != null)
           {
               layer.name = "Layer-" + i;
               parallaxLayers.Add(layer);
           }
       }
     }
     void Move(float delta)
     {
         foreach (ParallaxLayer layer in parallaxLayers)
       {
           layer.Move(delta);
       }
   }
 }
[ExecuteInEditMode]
 public class ParallaxLayer : MonoBehaviour
 {
       public float parallaxFactor;
       public void Move(float delta)
       {
           Vector3 newPos = transform.localPosition;
           newPos.x -= delta * parallaxFactor;
           transform.localPosition = newPos;
       }
 }
[ExecuteInEditMode]
 public class ParallaxCamera : MonoBehaviour 
 {
     public delegate void ParallaxCameraDelegate(float deltaMovement);
     public ParallaxCameraDelegate onCameraTranslate;
     private float oldPosition;
     void Start()
     {
         oldPosition = transform.position.x;
     }
     void Update()
     {
         if (transform.position.x != oldPosition)
         {
             if (onCameraTranslate != null)
             {
                 float delta = oldPosition - transform.position.x;
                 onCameraTranslate(delta);
             }
             oldPosition = transform.position.x;
         }
     }
 }

How it works: First you have to have a gameobject with the ParallaxBackground script and add the layers as children to this game object and put the ParallaxLayer script on these. Then all you have to do is call Move(delta) where delta is the distance that the ortho camera moved. I made an event in the parallax camera, but you can do as you will. The layers will move with parallaxFactor ( if parallaxFactor is 1 then the layer will move at the same speed as the camera, if it's 0.5 then it will move 2 times slower, 2 for 2 times faster)
I prefer the second method since it's more 2d ish, but I have used both methods and both work well.

0x12. SQLite

https://answers.unity.com/questions/743400/database-sqlite-setup-for-unity.html

     string conn = "URI=file:" + Application.dataPath + "/PickAndPlaceDatabase.s3db"; //Path to database.
     IDbConnection dbconn;
     dbconn = (IDbConnection) new SqliteConnection(conn);
     dbconn.Open(); //Open connection to the database.
     IDbCommand dbcmd = dbconn.CreateCommand();
     string sqlQuery = "SELECT value,name, randomSequence " + "FROM PlaceSequence";
     dbcmd.CommandText = sqlQuery;
     IDataReader reader = dbcmd.ExecuteReader();
     while (reader.Read())
     {
         int value = reader.GetInt32(0);
         string name = reader.GetString(1);
         int rand = reader.GetInt32(2);
        
         Debug.Log( "value= "+value+"  name ="+name+"  random ="+  rand);
     }
     reader.Close();
     reader = null;
     dbcmd.Dispose();
     dbcmd = null;
     dbconn.Close();
     dbconn = null;
 }

0x13. 记录编译时间

using System;
using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class MyBuildTest
{
    const string compilingKey = "Compiling";
    static bool compiling;
    private float time;

    static MyBuildTest()
    {
        compiling = EditorPrefs.GetBool(compilingKey, false);
        EditorApplication.update += Update;
    }

    static void Update()
    {
        if (compiling && !EditorApplication.isCompiling)
        {
            Debug.Log(string.Format("Compiling DONE {0}", DateTime.Now));
            compiling = false;
            EditorPrefs.SetBool(compilingKey, false);
        }
        else if (!compiling && EditorApplication.isCompiling)
        {
            Debug.Log(string.Format("Compiling START {0}", DateTime.Now));
            compiling = true;
            EditorPrefs.SetBool(compilingKey, true);
        }
    }
}

0x14. 单例

    #region Instance
    private static FoodManager mInstance;

    public static FoodManager Instance()
    {
        return mInstance ?? (mInstance = new FoodManager());
    }
    private void Awake()
    {
        mInstance = this;
    }
    #endregion

0x15. 二维数组

static void TwoDimensionalArray() 
        {
            int[,] array = new int[,] { { 1, 1, 1,1 }, { 2, 2, 2 ,2}, { 3, 3, 3 ,3}, { 4, 4, 4,4 },{ 4, 4, 4 ,4},{ 4, 4, 4 ,4} };//定义一个二维数组
          
            int col = array.GetLength(0);//获取指定维度中的元素数,即 行数


            int  row  = array.GetLength(1);//获取指定维度中的元素数,即 列数

           int number = array.Rank;    //获取二维数组中维数,例如 二维数组,row=2, 三维数组 ,row=3……

            int cols = array.GetUpperBound(0) + 1;//获取指定维度中的上限,有几个元素 int[N,],表示的N;

            int num = array.Length;//获取整个二维数组的长度,即所有元素的个数 

            Console.WriteLine("row" + row + "col" + col + "cols" + cols + "num" + num+"number"+number);
            Console.ReadLine();


            for (int i = 0; i < array.GetLength(0); i++)
            {
                for (int j = 0; j < array.GetLength(1); j++)
                {
                    Console.WriteLine("  " + array[i, j]);

                }
                Console.ReadLine();
            }
          
        }

0x16. TextMesh Pro字体

1.将要使用的字体文件导入unity,例如使用微软雅黑,就到系统字库中找到msyh.ttf,然后导入。2.新建一个文本文件txt,编码转成UTF-8,将要生成的文字输入到该文件并保存,将该文件导入到unity中
3.确认unity已经导入TextMesh Pro
4.在unity中打开window->TextMeshPro->Font Asset Creator
5.Source Font File选择msyh,我们刚才导入的字体
6.Sampling Point Size 选择Custom Size,然后在后面的字体大小中输入需要的字号
7.Character Set 选择Characters from File
8.Character File 选择我们已导入的txt文件
9.点击Generate Font Atlas
10.创建完成后,选择save保存
11·.创建测试,选择我们刚生成的Font Asset,然后输入中文测试。
12.注意能显示的中文只有我们导入的文本文件中的内容

转载必须注明来源: 小树技术博客 » Unity 常用代码段和知识点

0 条回应