Unity basic learning nine, Unity common API

1. Event Function: event function

  • Reset() : This event function is triggered when the script is attached and when Reset is pressed on the component of the game object
  • Start() : It will be executed once when the game is initialized
  • Update() : This method will be run every frame
  • FixedUpdate(): How many times this method will be called at the specified frame
  • LateUpdate(): Later than Update's running order, but FPS is the same as Update
  • Awake() Start() : It runs once when the game object is initialized, but the running order of Awake is higher than that of Start, and as long as there is an Awake method in the script, the method will be executed regardless of whether the script is mounted or not
  • OnEnable(): This method will be called automatically when the object's SetActive is set to true
  • OnDestory(): This method will be called when the game is closed

2. Time time class function

  1. Time.time represents the time from game development to the present, and will stop counting when the game is paused.
  2. Time.timeSinceLevelLoad indicates the time from the current Scene to the present, and it will also stop with the pause operation.
  3. Time.deltaTime represents the time from the previous frame to the current frame, in seconds. [Generally used to control the movement of characters and animations]
  4. Time.fixedTime indicates the start time of the game in seconds, and the fixed time is updated at regular intervals (equivalent to fixedDeltaTime) until the time property is reached.
  5. Time.fixedDeltaTime means that the interval is counted in seconds, and the physics and other fixed frame rates are updated. You can set it yourself in the Fixed Timestep of Edit->ProjectSettings->Time.
  6. Time.SmoothDeltaTime represents a smooth deltaTime, based on the time-weighted average value of the previous N frames.
  7. Time.timeScale Time scaling, the default value is 1, if set <1, it means time slows down, if set >1, means time speeds up, it can be used to speed up and slow down games, playback, etc., very useful. If Time.deltatime is used to control the movement in the game, you can pause its movement by setting Time.timeScale=0.
  8. Time.frameCount total number of frames
  9. Time.realtimeSinceStartup Indicates the total time since the game started, even if it is paused, it will continue to increase. [Generally used for performance testing]
  10. Time.captureFramerate means to set the frame rate per second, and then ignore the real time.
  11. Time.unscaledDeltaTime is calculated in seconds. The time to complete the last frame is the same as deltaTime regardless of timescale. If timescale is set, it is invalid.
  12. Time.unscaledTime The time from the start of the game to the present is the same as time when timescale is not considered. If timescale is set, it is invalid.
         /// <summary>获取秒级别时间戳(10位)</summary>
        public static long GetTimestampToSeconds()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }
 
        /// <summary>获取毫秒级别时间戳(13位)</summary>
        public static long GetTimeStampToMilliseconds()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds);
        }

3. GameObject class

3.1 Three ways to create game objects

  1. Create a GameObject through its constructor go=new GameObejct("Game Object Name"); //Usually used to create an empty game to store other things.
  2. Instantiate GameObject.Instantiate(prefab) //Create (clone Colon) based on Prefab or another game object, which can instantiate particles and other game objects, which is very commonly used
  3. CreattePrimitive GameObject.CreatePrimitive(PrimitiveType.**) //Create original game objects, basic geometry
  4. xxx.transform.SetParent(parent) configures the parent component

3.2 Adding components to game objects

The components can be our own custom scripts

GameObject.AddComponent<component name>();

3.3 Attributes, variables

  • GameObject.activeInHierarchy Whether the game object is active or not is related to the parent class. If the parent class is deactivated, the subclass is also deactivated
  • The active state of GameObject.activeSelf has nothing to do with the parent class, but only with itself. [The activation and deactivation of control components use .enable=false/true]
  • GameObject.tag The tag of the game object, specifically set by the programmer
  • GameObject.SetActive(false/true) Sets the active state of its game object through the control of parameters, true is the active state, and vice versa is the deactivated state.

3.4 Common methods and variables in UnityEngine.Object

  1. name : Name, if this variable is called, the name of the game object will be returned whether it is through GameObject or Component. gameObj.name
  2. GameObject.Find() uses the name to find a non-specific object in the field, which consumes performance and does not find things that are not active . GameObject target = GameObject.Find("name");//name is the name of the object to be found
  3. If you want to find hidden objects , use transform.Find(), only search under the sub-objects of this object, without recursion.
  4. Destroy() : Delete the game object, but it will not be deleted in unity immediately, but will be recycled first, and will be deleted when it is determined that no object is used. GameObject. Destroy(gameObj);
  5. DontDestroyOnLoad() : When loading a new scene, do not delete a game object in this scene. GameObject.DontDestroyOnLoad(gameObj);
  6. FindObjectOfType<>: Find  Image by type tImg = GameObject.FindObjectOfType<Image>();
  7. FindObjectsOfType <> : t is searched by type, it is a global search, and it is searched in the entire scene. Image[] tImgs = GameObject. FindObjectsOfType<Image>();
  8. FindGameObjectWithTag : If more than one is found, only the first one found will be returned. GameObject tGameObj = GameObject. FindGameObjectWithTag("tag");
  9. FindGameObejctsWithTag returns the set of found game objects. GameObject[] tGameObjs = GameObject. FindGameObjectsWithTag("tag");
  10.  Return all child objects of gameObj : int tCount = gameObj.transform.childCount; for (int i = 0; i < tCount; i++) Transform tChildTrans = gameObj.transform.GetChild(i);

            

3.5 Sending of messages 

  1. BroadcastMessage() broadcasts a message , Calls the method named  methodName on every  MonoBehaviour  in this game object or any of its children. All scripts on gameObj, including all scripts of child objects, execute the function of FunctionName. gameObj.BroadcastMessage("FunctionName", "FunctionParam", SendMessageOptions.RequireReceiver);
  2. SendMessage() sends a message , only to methods on the script in this game object . gameObj.SendMessage("FunctionName", "FunctionParam", SendMessageOptions.RequireReceiver);
  3. SendMessageUpwards() broadcasts and sends messages, calls its own methods, and calls the methods of its parent object (gameObj.parent), and calls its parent object's parent object (gameObj.parent.parent)........all parent object. gameObj.SendMessageUpwards("FunctionName", "FunctionParam", SendMessageOptions.RequireReceiver);

3.6 Search for game components

  1. Cube cube = target.GetComponent<Cube>(); Return a corresponding component, if there are multiple, only return the first one
  2. Cube[]cc= target.GetComponents<Cube>(); Return all eligible components on the game object and return an array of components
  3. Cube[] xx = target.GetComponentsInChildren<Cube>(); Return any of its children using the game object component
  4. Cube[] yy = target.GetComponentsInParent<Cube>(); Returns the corresponding component on the game object, and returns the corresponding component on the parent object of the game object, target.parent.parent.parent....... .

 4. MonoBehaviours class

4.1 Inherited variable members

  1. enabled : Returns whether the component is activated or disabled, which can be set through this variable. this. enabled
  2. isActiveAndEnabled : It can only return the flag of whether the component is active, and cannot set this variable, which is read-only. this.isActiveAndEnabled
  3. tag : the tag of the game object corresponding to this component
  4. name : the name of the game object corresponding to this component

4.2 Invoke and other methods and variables

  1. Invoke("method", float time): call the method after waiting for time  Invoke("TempFunction", 1f);

        public void TempFunction()

        {

            Debug.Log("fdsafads");

        }

  2. bool i= IsInvoking("method 1") returns a bool value, if the method is added to the queue but not executed, it will return true, if the method is called after a period of time, it will return false;
  3. InvokeRepeating("method 1",delayTime,repeatTime) : After waiting for time, method 1 will be run repeatedly, once  every number seconds. InvokeRepeating("TempFunction",10f,1f);
  4. CancelInvoke()  will suspend the operation through Involve/InvokeRepeating, but generally speaking, CancelInvoke will be called in combination with InvokeRepeating. Parameters are set by yourself

4.3 Expansion

Add [ExecuteInEditMode] before the script class : the script will start compiling without pressing the game play button, only in the edit mode.

Add [HideInInspector] before the common variables of the script , and the common variables will not be displayed in the Inspector panel.

 

5. Coroutines: coroutines:

5.1 Define coroutines

IEnumerator method name()

StartCoroutine(TempFunction());

    public  IEnumerator TempFunction()
    {
        Debug.Log("fdsfdssf");
        yield return new WaitForSeconds(5.0f); //等待一定时间在运行下面的代码
        Debug.Log("222222");
    }

5.2 Turning on and off coroutines

The parameters of StartCoriutine (parameter) and StopCoroutine (parameter) should correspond to each other. If the method name is passed, the parameter in the two methods must be the method name. If it is the return value of IEnumerator, the parameters sent by the two methods It is the return value of IEnumerator.


    public  IEnumerator TempFunction()
    {
        Debug.Log("fdsfdssf");
        yield return new WaitForSeconds(5.0f); //等待一定时间在运行下面的代码
        Debug.Log("222222");
    }

or

 5.3 StopAllCoroutines() Stop all coroutines, no matter how you call them

6. OnMousexx mouse trigger event

If the trigger detection is performed through Collider, it is necessary to enable ray detection in the settings.

  1. OnMouseDown() : Triggered when the mouse is pressed, press once to trigger  private void OnMouseDown(MouseDownEvent evt)
  2. OnMouseDrag() : Triggered all the time when the mouse is held down, it is triggered every frame void OnMouseDrag(MouseMoveEvent evt)
  3. OnMouseUp() : Triggered when the mouse is lifted, only executed once  private void OnMouseUp(MouseUpEvent evt)
  4. OnMouseEnter() : Triggered when the mouse enters, once entered  public void OnMouseEnter()
  5. OnMouseOver() : When the mouse is on top of the trigger object,  void OnMouseOver() is always triggered
  6. OnMouseExit() : trigger public void OnMouseExit() when the mouse moves out 
  7. OnMouseUpAsButton() is equivalent to the function of a button. It will be triggered when the mouse is pressed and lifted on the same game object, and it will not be triggered if the mouse is pressed and lifted on a different object.

7. Mathf class: all members are static

  1. Mathf.Abs() returns the absolute value of
  2. Mathf.Ceil() is rounded up, 10.1--->11
  3. Mathf.Clamp(value, min, max) returns value if the value of value is between min--max, but if the value of value is less than min, it returns min, and if the value of value is greater than max, it returns max, generally It is used to control the character's blood volume. When the player's blood volume decreases, it will not appear below 0 and above 100. hp= Mathf.Clamp(hp,0,100);
  4. Mathf.ClosePowerOfTwo(value): Get the closest value to the power of 2 of value
  5. Mathg.DeltaAngke : Get the minimum angle between two angles
  6. Mathf.Floor rounded down
  7. Mathf.Pow(i,j) gets i to the power of j
  8. Mathf.MoveToWards() is generally used for movement control, which is a uniform movement with a fixed acceleration
  9. Mathf.Lerp() difference operation is generally used to control animation and movement, the slower it runs as it goes backwards. Mathf.Lerp(0.0f, 100.0f,0.5f) = 50.0f
  10. Mathf.PingPong(t,maxValue) is similar to the back and forth movement of table tennis. The initial value is 0. The t variable controls the value to move from 0 to maxValue. When t is greater than maxValue, it moves to 0 again, and then it goes back and forth like this. For reciprocating motion, the general t variable is controlled by Time.deltatime.

8.Input input class

  1. GetKey() is triggered when the button is pressed all the time 
        if (Input.GetKey(KeyCode.Space))
        {
            Debug.Log("Shooting a bullet while SpaceBar is held down");}
  2. GetKeyDown() is triggered when the button is pressed
  3. GetKeyUp() is triggered when the button is pressed and then lifted
  4. GetMouseButton(0/1/2) 1: Left button 2: Right button 3: Triggered when the middle mouse button is pressed all the time  if(Input.GetMouseButton(0))
                Debug.Log("Pressed left click.");
  5. GetMouseButtonDown(0/1/2) is triggered when the mouse is pressed,
  6. GetMouseButtonUp(0/1/2) is triggered when the mouse is lifted up
  7. GetButtonDown()
  8. GetButton()
  9. The three parameters of GetButtonUp() are user-defined virtual buttons to trigger, and the others are the same as above
  10. GetAxis("virtual axis name") returns the value between -1 and 1 by pressing the virtual axis, the initial value is 0, and then gradually changes to -1/1, with a certain acceleration. Generally used to control the movement, such as the acceleration movement of the car, etc. (GetAxis("Mouse X"),
    GetAxis("Mouse Y"),
    GetAxis("Mouse ScrollWheel"),
    GetAxis("Vertical "),
    GetAxis("Horizontal "),
        1.Mouse X triggers when the mouse moves along the screen X
        2.Mouse Y triggers when the mouse moves along the screen Y
        3.Mouse ScrollWheel triggers when the mouse scroll wheel scrolls
        1.Vertical corresponds to the up and down arrows on the keyboard, when pressed 2.Horizontal corresponds to the left and
        right arrows on the keyboard, and is triggered when the left or right arrow is pressed
  11. GetAxisRaw() Others are similar to GetAxis, except that the gradient effect is missing, and the return value is only 0 1 -1
  12. anyKeyDown returns true when any key is down (including mouse buttons)
  13. anyKey returns true when any key is pressed (including the mouse)
  14. mousePosition returns the pixel coordinates of the mouse on the screen, [screen coordinates] Vector2 with a z-axis balance of 0 screenpos = Input.mousePosition;

9.Vector3: three-dimensional variable

  1. Cross() interpolation and multiplication operation [left-hand rule], through two vectors to obtain the direction of another vector, and then make related judgments  Vector3.Cross(Vector3,Vector3):float
  2. Project() projection operation
  3. Reflect() reflection operation
  4. Slerp() performs interpolation according to the angle, and lerp interpolates according to the position information, which is generally used in the rotation of the fort to make the rotation smoother
  5. Vector3.Dot(Vector3,Vector3):float 点积

11.Random random number class

  1. InitState() : The seed specified by the parameter, and then calling Range() to generate random numbers will be generated according to the seed, so the random numbers generated in each run are the same, which is a pseudo-random number. Generally, the random numbers to be generated are different, and the parameter can be set to System.DataTime.Now.Ticks:  Random.InitState(seek);
  2. insideUnitFCircle : Randomly generate a position information in a circle with a unit of 1. If you want to generate it in a larger circle, you can * circle radius information later. Generally used to control the location information of randomly generated enemies. Vector2 newPosition  Vector2 = Random.insideUnitCircle * 5 ; transform.position.x = newPosition.x ; transform.position.y = newPosition.y ;
  3. insideUnitSphere : Randomly generate a position information in a sphere with a unit of 1. If you want to generate it in a larger sphere, you can *circle radius information later. transform.position = Random.insideUnitSphere * 5;

12. Quaternion:

Euler angle [eylarAngles] can be converted between the corresponding value in the panel and the quaternion [rotation]. Generally, the Euler angle is used to let the user see it intuitively , and the quaternion is used to control internal operations .

  1. .eulerAngles converts quaternions into Euler angles  transform.eulerAngles = new Vector3(10, yRotation, 0);
  2. Quaternion.Euler() converts Euler angles to quaternions 
    Quaternion rotation = Quaternion.Euler(0, 30, 0);
  3. .LookRotation() allows the player to rotate to look at the enemy by setting the quaternion, and convert the vector direction into a quaternion  car.rotation = Quaternion.LookRotation(pos2 - pos1);
  4. Quaternion.Slerp()  does slow rotation                                                                                                player.rotation = Quaternion.Slerp(player.rotation, target, Time.deltaTime); // interpolated slow rotation

13. Rigidbody: Rigid body component, which controls the movement of the character

  1. .position: The movement can be controlled by the rigid body. In terms of controlling the movement, using rigibody.positionon is much faster than transform.porition. The related physical calculations are also calculated in the rigid body, but it is not recommended to use this method for continuous The movement of the control object is not smooth. You can also use MovePosition() to optimize the position when you control it once or twice , which uses interpolation calculations. Generally, this method is used for continuous movement, and there is no stuttering phenomenon.  
            Vector3 dir = new Vector3(h, 0, v);
            //The characteristics of rigid body movement: the position + direction of the object, if it is too fast, the direction * a decimal, make it slower
            mmRigidbody.MovePosition(mmTransform.position + dir * 0.2f);
  2. rotation: MoveRotation() is used to control the rotation of the rigid body. It is generally not recommended to use rotation, which consumes more performance. It is recommended to use MoveRotation() , and then use it with Quaternion.slerp() to make it smoother.
            Quaternion deltaRotation = Quaternion.Euler(m_EulerAngleVelocity * Time.fixedDeltaTime);
            m_Rigidbody.MoveRotation(m_Rigidbody.rotation * deltaRotation);
  3. AddForce() Adds force to a rigid body, which can generally be used in racing games. When accelerating for a short time, it can be given a limited time AddForce method

14.Camera; camera component

Camera.ScreenPointToRay()

When the label of the camera is main cream, you can use Camera.main to search the ray of the scream component of the main camera to detect the position information of the mouse on the screen and what it touches

Ray ray = cameraMain.ScreenPointToRay(Input.mousePosition); //获得相机到鼠标之间的射线
RaycastHit hit; //用来存放射线检测到的游戏物体的信息的
bool temp = Physics.Raycast(ray, out hit); //进行射线检测

15.Application 

  1. /StreamingAssets : The resources under this file will not be compressed, what type or type to import, [mainly audio and video resources]
  2. dataPath : project file path 
    m_Path = Application.dataPath;
  3. Application.streamingAssetsPath (read-only) : The file path that can be read through file streaming
  4. Application.persistentDataPath (read and write) : the file path that can be instantiated
  5. temporaryCachePath : temporary file path
  6. Application.OpenURL("") opens the specified URL
  7. Application.Quit() exits the running of the game
  8. .CapturScreenshot("game screenshot") is used for screenshot, the string is screenshot fileName
  9. Application.identifier identifier name
  10. .companyName company name
  11. productName product name
  12. instalMode installation package name
  13. isEditor is in editor mode
  14. isFocused is in focus
  15. isMoliePlatform is a mobile platform
  16. isPlaying
  17. isWebPlayer
  18. platform The platform of the editor
  19. unityVersion unity version number
  20. version project file version number
  21. Whether runInBackground can run in the background
  22. UnityEditor.EditorApplication.isPlaying=false; //Exit the editing state in editor mode

16. SceneManager scene class 

  1. SceneManager.LoadScene() loads the next scene, which is generally used when another scene is not too large
  2. SceneManager.LoadSceneAsync() loads the next scene asynchronously, and returns the AsyncOperation type, which contains the loading information, the loading progress bar, and so on. Allows users to ease the time spent waiting for scenes to load.
    
        public Slider _progress;
        void Awake()
        {
            _progress = GetComponent<Slider>();
        }
        //使用协程
        void Start()
        {
            StartCoroutine(LoadScene());
        }
     
        IEnumerator LoadScene()
        {
            //用Slider 展示的数值
            int disableProgress = 0;
            int toProgress = 0;
     
            //异步场景切换
            AsyncOperation op = SceneManager.LoadSceneAsync("Line");
            //不允许有场景切换功能
            op.allowSceneActivation = false;
            //op.progress 只能获取到90%,最后10%获取不到,需要自己处理
            while (op.progress < 0.9f)
            {
                //获取真实的加载进度
                toProgress = (int)(op.progress * 100);
                while (disableProgress < toProgress)
                {
                    ++disableProgress;
                    _progress.value = disableProgress / 100.0f;//0.01开始
                    yield return new WaitForEndOfFrame();
                }
            }
            //因为op.progress 只能获取到90%,所以后面的值不是实际的场景加载值了
            toProgress = 100;
            while (disableProgress < toProgress)
            {
                ++disableProgress;
                _progress.value = disableProgress / 100.0f;
                yield return new WaitForEndOfFrame();
            }
            op.allowSceneActivation = true;
        }
  3. sceneCount gets the number of currently loaded scenes
  4. sceneCountInBuildSettings The number of scenes loaded in the Build panel
  5. GetActiveScene() Gets the information of the current scene that has been loaded
  6. GetSceneAt(index) loads the scene indexed by index
  7. The following event is triggered when a new scene is loaded: SceneManager.activeSceneChanged This event is called when a new scene is loaded. SceneManager.sceneLoaded triggers this event when a new scene is loaded.
    // += 表示注册这个方法,一旦场景变更,就触发
    SceneManager.activeSceneChanged += ChangedActiveScene;
    //以及
    SceneManager.sceneLoaded += OnSceneLoaded;
    
        void OnSceneLoaded(Scene scene, LoadSceneMode mode)
        {
            Debug.Log("OnSceneLoaded: " + scene.name);
            Debug.Log(mode);
        }
    
        private void ChangedActiveScene(Scene current, Scene next)
        {
            string currentName = current.name;
    
            if (currentName == null)
            {
                // Scene1 has been removed
                currentName = "Replaced";
            }
    
            Debug.Log("Scenes: " + currentName + ", " + next.name);
        }
  8. Expansion: The event is registered by adding a method : SceneManger.activeSceneChanged+=OnAcitiveSceneChanged;

17. Radiographic inspection

Generally, ray detection should be within the range of ray detection, and the object to be detected must have a Collider

Ray ray=new Ray(起点,方向);
PaycastHit hit; //hit中存放的是射线检测的碰撞信息
bool temp=Physics.Raycast(ray,out hit); //具体的重载方法边用边查
Ray ray = new Ray(this.transform.position + transform.forward, transform.forward); //创建射线
RaycastHit hit; //存储射线检测到的游戏物体信息
if(Physics.Raycast(ray,out hit)) //通过返回值来判断射线是否检测到相关的物体了
{
    Debug.Log(hit.collider.gameObject.name);
}

expansion:

Raycast ; The detection is the first object that the ray hits, not penetrating  bool temp = Physics.Raycast(ray,out hit);

RaycastAll : Returns a RaycastHit array, which is penetrative and can return multiple detected game objects. bool temp = Physics.Raycast(ray,out hit);

            Ray ray = new Ray();
            RaycastHit[] hits = Physics.RaycastAll(ray);

18. Code listens for trigger events 

  1. <Button>().onClick.AddListener(method name) ; //When the button component is triggered, the method with the specified method name will be triggered
        private void Start()
        {
            btn3.GetComponent<Button>().onClick.AddListener(OnClickBtn3);
        }
        void OnClickBtn3()
        {
            Debug.Log("Click3");
        }

Register to listen to events by implementing the interface:

  1. using UnityEgine.EventSystems; import namespace
  2. IPointerDownHandler mouse down event interface, specific interface reference manual 
    public class ScrollButton : MonoBehaviour,
        IPointerDownHandler,IPointerUpHandler, IPointerClickHandler
    {
        //实现了这三个接口,就得实现这三个方法
        public void OnPointerDown(PointerEventData eventData)
        {
            isDown = true;
        }
        public void OnPointerUp(PointerEventData eventData)
        {
            isDown = false;
        }
        public void OnPointerClick(PointerEventData eventData)
        {
            if (Time.time - lastUpBtnTime <= DelayTime)
            {
                ChangeBarValueByBtn(ClickType.Once);
            }
        }
    }
  3. Raycast Target: If you cancel the check of this option on the panel, you will not do event monitoring, and you will not be able to achieve key detection.

19.www class, download

It is used to download resources in the network.

  public string url = "http://img.taopic.com/uploads/allimg/120727/201995-120HG1030762.jpg";

  IEnumerator Start()
  {
      WWW www = new WWW(url);
      yield return www;
      Renderer renderer = this.GetComponent<Renderer>();
      renderer.material.mainTexture = www.texture;
  }

20.Touches touch event

 Input.touches: returns the finger information placed on the screen, returns an array 

 Touch touch1=Input.touches[0];
 touch1.position;
 TouchPhase pahse = touch1.phase //phase 是用来返回手指的状态的

21.Debug.DrawRay(ray.oridin,ray.direction) draw rays

The first parameter is the origin, the second is the direction

22.CharacterController role controller

  1. .SimpleMove(vector3) simple movement
  2. .isGrounded determines whether it is on the ground, bool value
  3. The difference between .Move() and simpleMove() is that .Move() requires *Time.deltatime , and simpleMove will use its own gravity
  4. OnControllerColliderHit(ControllerColliderHit hit) This event function will be triggered when there is a collision with other colliders [hit saves the information of the collided object]
        void OnControllerColliderHit(ControllerColliderHit hit)
        {
        }

23. Mesh settings

Material mesh specifies what a person looks like, and material specifies what a person's skin color looks like

24. API changes

Deprecated: Application.LoadLevel();

New: SceneManager.LoadScene(); Loads a new scene

New: Scene scene=SceneManager.GetActiveScene(); //Get the information of the current active scene

SceneManger.LoadScene(scene.buildIndex) //Reload the current scene

Deprecated: OnLevelWasLoaded() Called when the scene is loaded.

Changed to event: SceneManager.sceneLoaded

25. Collision body detection body

Trigger detection:

    private void OnTriggerEnter(Collider other)
    {
        speed = speed * -1;
    }

Impact checking: 

void OnCollisionEnter(Collision collision)
{
      //在脚本中添加这个函数,如果发生碰撞则执行此函数
}

quote

Unity commonly used API (feeling very practical)

Guess you like

Origin blog.csdn.net/u013617851/article/details/123859111