Unity 3D Tips

Because I have a bit of a Goldfish memory at times, this page contains a list of the various Unity tips that I have picked up on my travels, I share them not only to enlighten others, but also so I do not forget them :) .

General

  • How do I make a class serialisable?

    [Serializable]
    public class SaveData
    {
    }
    
  • How do I open an URL in the browser?

    Application.OpenURL("http://www.drmop.com");
    
  • How do I load another scene?

    SceneManager.LoadScene("AnotherScene");
    
  • How do I check for the back button being pressed on Android?

    if (Input.GetKeyDown(KeyCode.Escape))
    {
    }
    
  • How do I instantiate a prefab?

    GameObject obj = Instantiate(my_prefab, position, orientation) as GameObject;
    
  • How do I change the parent of a game object?

    my_object.transform.SetParent(parent_object.transform);
    
  • How do I get the main camera in the scene?

    Camera main_cam = Camera.main;
    
  • How do I get the first child of a game object?

    Transform first_child = game_object.GetChild(0);
    
  • How do I get a named child of a game object?

    Transform child = game_object.FindChild("childs_name");
    
  • How do I define and start a coroutine?

    // Define the coroutine
    private IEnumerator RunTests()
    {
        for (int t = 0; t < 100; t++)
        {
            // Run the test at index t then wait for 2 seconds
            RunTest(t);
            yield return new WaitForSeconds(2);
        }
    }
    // Start the coroutine
    StartCoroutine(RunTests());
    
  • How do I call a method after a delay?

    // Define a coroutine that cals the method after a delay
    private IEnumerator CallMethodAfterDelay(float delay, Action method)
    {
        yield return new WaitForSeconds(delay);
        method();
    }
    // Start the coroutine
    StartCoroutine(CallMethodAfterDelay(10, my_delayed_method));
    

Collision and hit testing

  • How do I found out which object was touched on the screen?

    private HitObject? FindHitObject(Vector3 pos)
    {
        Ray r = Camera.main.ScreenPointToRay(pos);
        RaycastHit hit;
    
        if (Physics.Raycast(r, out hit, Mathf.Infinity))
        {
            GameObject go = hit.transform.gameObject;
        }
        return null;
    }
    

Maths

  • How do I make an object face the camera or another object?

    transform.rotation = Quaternion.LookRotation(cam_or_object.transform.position - transform.position);
    
  • How do I position an object in the direction of another object?

    // Set the objects position so that it is distance units in front of the source object in the direction it is facing
    Vector3 dir = source_object.transform.rotation * new Vector3(0, 0, distance);
    transform.position = source_object.transform.position - dir;
    

3D

  • How do I change the text and colour of 3D Text?

    TextMesh tm = go.GetComponent<TextMesh>();
    tm.text = "Hello";
    tm.color = Color.blue;
    
  • Animation

    • How do I make an animation relative?
      Unity doesn’t appear to support relative animation key frames so instead you have to create an empty game object then place the object with its animation inside it. You can then position the parent game object to wherever you would like the object to start its animation.

    Materials and Textures

    • How do I change the material of a mesh?

      MeshRenderer mr = my_object.GetComponent<MeshRenderer>();
      mr.material = new_material;
      
    • How do I change the texture of a material?

      MeshRenderer mr = my_object.GetComponent<MeshRenderer>();
      mr.material.texture = new_texture;
      

    Networking

    • How do I download a file from the web?

      using UnityEngine.Networking;
      IEnumerator DownloadFile()
      {
          UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Get("http://www.drmop.com/acoolfile.txt");
          yield return www.Send();
          if (!www.isError)
          {
              Debug.Log(www.downloadHandler.text);
          }
      }
      

    UI

    • How do I get the size of an UI element?

      RectTransform rt = GetComponent<RectTransform>();
      Rect rect = rt.rect;
      
    • How do I change the size of an UI element?

      RectTransform rt = GetComponent<RectTransform>();
      rt.sizeDelta += new Vector2(new_size.x - rt.rect.width, new_size.y - rt.rect.height);
      
    • How do I get the parent canvas for an UI element?

      Canvas parent = GetComponentInParent<Canvas>();
      
    • How do I hide an UI element?

      transform.localScale = new Vector3(0, 0, 0);
      
    • How do I change the sprite of an UI element?

      MusicButton.GetComponent<Image>().sprite = new_sprite;
      

    Leave a Reply