Hi guy, Im stucking on an asynchronous problem with async, await.
This is my code
private List<LessonDTO> chapters;
void Start()
{
GetData();
title.text =String.Format("HỌC KÌ {0}", LessonManager.GetInstance().GetSemester());
first.text = String.Format("Chương {0}",chapters[0].chapter.ToCharArray()[0]);
second.text = String.Format("Chương {0}", chapters[1].chapter.ToCharArray()[0]);
third.text = String.Format("Chương {0}", chapters[2].chapter.ToCharArray()[0]);
}
// Update is called once per frame
void Update()
{
}
async void GetData(){
var lessonBus = new LessonBUS();
chapters = await lessonBus.GetChapterBySemester(LessonManager.GetInstance().GetSemester());
}
I have also tried the GetData() in the Awake function but still, left with NullRefereneException at Awake.
Im not familliar with asynchronous im really thankful if someone help me with my problem.
Many thanks!
The answer is always the same… ALWAYS!
How to fix a NullReferenceException error
https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/
Three steps to success:
- Identify what is null ← any other action taken before this step is WASTED TIME
- Identify why it is null
- Fix that
1 Like
Your error is in line 35 according to the message.
Attach the debugger, set a breakpoint, debug. 100% never have to guess anymore by inspecting your code as it executes.
2 Likes
Your code seems to have some general logic issue. Namely you call GetData in start but it’s an async method, so it runs asynchronously. That means the “chapters” that are set once the await call finishes are not set when the rest in your Start method executes. The Start method will NOT wait for your async method to finish. This only happens in synchronous methods (so non-async methods).
So you can make your Start method also an async method and await your GetData method before you use your data. This would be the usual approach.
Apart from that you use some kind of singleton in your code LessonManager.GetInstance()
. We don’t know what kind of singleton that is and if your GetInstance method does lazy load the single instance or not. If not it could return null.
2 Likes