NullReferenceException was thrown when raise an event
I want to implement the communication between GameObjects via Event. But a NullReferenceException was thrown when raise an event.
public class PathController : MonoBehaviour
{
public event EventHandler FileSended;
void Start()
{
......
try
{
//Copy the file.
File.Copy(path, destpath, true);
if (FileSended != null)
{
FileSended(this, EventArgs.Empty);//Throw an Exception
}
}
catch (Exception ex)
{
Debug.LogError(ex.ToString());
}
......
}
}
The component above is attached to Empty GameObject PathController. The component belowis attached to Empty GameObject SerialController. Both GameObjects are on the same scene.
public class SerialController : MonoBehaviour
{
void Awake()
{
SerialIni.LoadSerialIni();//加载ini设置
GameObject.Find("PathController").GetComponent<PathController>().FileSended += OnFileSended;
}
// Use this for initialization
void Start()
{
......
//GameObject.Find("PathController").GetComponent<PathController>().FileSended += OnFileSended;
......
}
}
When I subscribe the event on Awake(), it will throw an exception. The exception information is below: System.NullReferenceException: Object reference not set to an instance of an object at SerialController .OnFileSended (System.Object sender) [0x00007] in C:\Users\MyPC\Desktop\MyGame\Assets\Scripts\SerialController .cs:402 at PathController+c__Iterator1.MoveNext () [0x0007b] in C:\Users\MyPC\Desktop\MyGame\Assets\Scripts\PathController.cs:118 When I subscribe the event on Start(), it will NOT throw an exception.But the function OnFileSended(object sender, EventArgs e)(as showed below) will never run.
public void OnFileSended(object sender, EventArgs e)
{
if (sp.IsOpen)
{
byteForWrite[0] = CODEFILE;
sp.Write(byteForWrite, 0, 1);
}
}
How can i do to Fix it?It would be great if someone could help me.
Your answer
Follow this Question
Related Questions
Event NullReferenceException 1 Answer
Null Reference Exception 0 Answers
Output from XML. NullReferenceException. 0 Answers
iOS exposed object properties are null 0 Answers