Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

继承自MonoBehaviour的类,成员变量初始化不执行 #492

Closed
l-xuanzi opened this issue Apr 29, 2021 · 2 comments
Closed

继承自MonoBehaviour的类,成员变量初始化不执行 #492

l-xuanzi opened this issue Apr 29, 2021 · 2 comments

Comments

@l-xuanzi
Copy link

l-xuanzi commented Apr 29, 2021

 class SomeMonoBehaviour : MonoBehaviour
    {
        float time;
        private Button button;
        private string testStr = "ddddddddddddddddddd"; 
        private TestClass tc = new TestClass("somenono `成员初始化");`//不会被初始化!!!!
        void Awake()
        {
            Debug.Log("dd2");
            Debug.Log("!! SomeMonoBehaviour.Awake" + testStr);

            TestClass t = new TestClass("mono Awake");
        }
    }
    public class TestClass
    {
        public TestClass2 tc2 = new TestClass2("testclass 成员初始化");//能被正常执行
        public TestClass(string str)
        {
            Debug.Log("testClass:" + str);
        }
    }
    public class TestClass2
    {
        public TestClass2(string str)
        {
            Debug.Log("testClass2" + str);
        }
    }
@liiir1985
Copy link
Collaborator

设计如此,MonoBehaviour Unity不允许手动调用构造函数,手动调用会报错,字段初始化是构造函数中的,因此无法初始化,请在Awake方法里初始化

@l-xuanzi
Copy link
Author

l-xuanzi commented May 6, 2021

@liiir1985 我在AddComponent方法的重定向中先调用了构造函数,再调用Awake,代码运行正常。

     ilInstance.CLRInstance = clrInstance;
     res = ilInstance;

     var m = type.GetConstructor(ILRuntime.CLR.Utils.Extensions.EmptyParamList);
     if (m != null)
     {
         __domain.Invoke(m, res, null);
     }

     clrInstance.Awake(); //因为Unity调用这个方法时还没准备好所以这里补调一次

请问我我这么写会有什么隐患吗?因为目前看来代码运行还没遇到问题。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants