Object reference not set to an instance of an object. System.NullReferenceException: Object reference not set to an instance of an object. code example

Example 1: object reference not set to an instance of an object in c#

You need to initialize the list first:

protected List<string> list = new List<string>();

Example 2: null reference exception object reference not set to an instance of an object unity

/**
To fix this, we can acquire a reference to an instance of the script using GameObject.
Find to find the object it is attached to. 
We then use GetComponent to find the script component we want a reference to.
**/

public calss MyScript : MonoBehaviour
{
	MySecondScript secondScript;
    void Start()
    {
    	secondScript = GameObject.Find("Second Script Object").GetComponent<MySecondScript>();
        
        Debug.Log(secondScript.firstName)
    }
}