Scripting

Table of Contents

Execution Order of Event Functions discussion

Awake vs Start discussion

HideInInspector vs NonSerialized vs SerializeField discussion

HideInInspector

public class ExampleClass : MonoBehaviour {
    [HideInInspector]
    public int p = 5;
}

SerializeField

public class SomePerson : MonoBehaviour
{
    //This field gets serialized because it is public.
    public string name = "John";

    //This field does not get serialized because it is private.
    private int age = 40;

    //This field gets serialized even though it is private
    //because it has the SerializeField attribute applied.
    [SerializeField]
    private bool hasHealthPotion = true;
}

Serialization discussion

Many of unity features build ontop of the serialization system:

[Serializable]
class Animal
{
    public string name;
}

class MyScript : MonoBehaviour
{
    public Animal[] animals;
}

Don't define a Coroutine named Main discussion

Don't define a coroutine named Main.

I wrote a coroutine named Main. It executed twice, in an unexpected way.

I've tweaked many times to understand why. Main executed even I didn't explicitly call StartCoroutine.

At last, I renamed Main to Main2, and it worked all the way I expected.

SendMessage reference

OnBecameVisible / OnBecameInvisible reference

Object reference

Instantiate

// Preferred
public static T Instantiate(T original);
public static T Instantiate(T original, Transform parent);
public static T Instantiate(T original, Transform parent, bool worldPositionStays);
public static T Instantiate(T original, Vector3 position, Quaternion rotation);
public static T Instantiate(T original, Vector3 position, Quaternion rotation, Transform parent);

// 'as T' required for type
public static Object Instantiate(Object original);
public static Object Instantiate(Object original, Transform parent);
public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);

Instantiated GameObject

  1. Before Instantiate
  2. Awake of Instantiated GameObject
  3. After Instantiate
  4. Start of Instantiated GameObject

Destroy

public static void Destroy(Object obj, float t = 0.0F);

GameObject reference

Create Empty with Code

GameObject player;
player = new GameObject("Player");
player.AddComponent<Rigidbody>();
player.AddComponent<BoxCollider>();

FindWithTag

respawn = GameObject.FindWithTag("Respawn");

Coroutine reference

C# classes need to have its own script with the class' name? discussion