Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

The Unity of small science

As always, here are some popular science tips from Unity:

  • Unity is a real-time 3D interactive content creation and operation platform.
  • All creators, including game development, art, architecture, car design, film and television, use Unity to bring their ideas to life.
  • The Unity platform offers a comprehensive suite of software solutions for creating, operating and monetizing any real-time interactive 2D and 3D content on mobile, tablet, PC, game console, augmented reality and virtual reality devices.
  • You can also simply think of Unity as a game engine that can be used to make professional games!

Learn Unity

Keep the game object in the previous scene from being destroyed after switching scenes

Many games and applications run in more than one scene, requiring a scene view switch. Switching scenes in Unity is simple and can be explained in a few sentences

However, after scene swapping in Unity, all game objects in the previous scene are destroyed by default

Sometimes we don’t want some game object or script to be destroyed for global control

So you have to control a game object through code and not destroy it when you switch scenes

The method is also very simple, the code is as follows:

Object.DontDestroyOnLoad(Object)
Copy the code

Just execute this method once in the script and add objects that you don’t want destroyed when switching scenarios

The effect is as follows:

The full code is here:

public class UnityTest1 : MonoBehaviour
{
    public Button button1;
    void Start()
    {
        DontDestroyOnLoad(this);
        button1.onClick.AddListener(SwitchScene);
    }
    void SwitchScene()
    {
        SceneManager.LoadScene("Scene2"); }}Copy the code

This way, the gameobject will not be destroyed as the scene changes


Use of GetType and Typeof

GetType and typeof in C# both return the data Type system.type referenced by an instance.

  1. GetType(), this method inherits from Object, so any Object in C# has a GetType() method, x.goettype (), where x is the variable name
  2. typeof(), () must be a concrete class name, type name, etc., cannot be a variable name
  3. System.type.gettype (), with two overloaded methods

The following is an example:

public class Unitytest1 : MonoBehaviour
{
    void Start()
    {
        Type a = typeof(Unitytest1);
        var b = Type.GetType("Unitytest1");
        var c = this.GetType();

        Debug.Log("Value of A:" + a);
        Debug.Log("Value of B:" + b);
        Debug.Log("Value of C:"+ c); }}Copy the code

Print result:


You can use GetType and TypeOF to return the data Type System.type that an instance specifically references

And then do something else with that data type!