New GameObject return null, in Editor mode.

New GameObject return null, in Editor mode.

It happen in Unity3D Editor mode.

When I want to auto create a folder like structure, and error show in console.

void Reset()
{
GameObject go = new GameObject("Sub-Folder");
go.transform.SetParent(transform); // Null reference "go == null"
}

the code above will fail. due to “go” value is null.
so the solution is simple.
DON’T process “new GameObject(blah)” within Editor session.
I prefer using “Invoke” hack in this case.

void Reset()
{
Invoke(nameof(Editor_Init), 0); // try not to use "string" type here, 
// instead we can use nameof() to label which function call we using.
// process in next ZERO second is a hack, to run the same thing without error. } void Editor_Init() { GameObject go = new GameObject("Sub-Folder"); go.transform.SetParent(transform); // will work like this. ya~~~ }

 

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料