当前位置:网站首页>Unity stepping on the pit record: if you inherit monobehavior, the constructor of the class may be called multiple times by unity. Do not initialize the constructor

Unity stepping on the pit record: if you inherit monobehavior, the constructor of the class may be called multiple times by unity. Do not initialize the constructor

2022-06-10 17:54:00 God of Luo Xiu

The conclusion is as follows :
Inherited Monobehaviour Class , It's not just constructors , But the whole construction process will be unity Spiritual execution many times

There is a problem in writing

public class TestScript : MonoBehaviour 
{
    
    
	TestObject1 testObject1 = new TestObject1();// By new many times , In fact, multiple objects are generated 
	TestObject2 testObject2;
    public TestScript()
    {
    
     
        testObject2 = new TestObject2();// By new many times , In fact, multiple objects are generated 
    }
}

Write it correctly :

public class TestScript : MonoBehaviour 
{
    
    
	TestObject1 testObject1;// Just a statement 
	TestObject2 testObject2;// Just a statement 
    void Awake()
    {
    
    
        testObject1 = new TestObject1();// stay Awake In the initialization , It's just new once 
        testObject2 = new TestObject2();// Same only new once 
    }
}

summary :
stay Unity in , Inherited from Monobehaviour When instantiating a class of , All construction statements may be Unity Execute many times ( Including member declarations and constructors ), We cannot avoid this process . So don't do any initialization during the construction of these classes , Otherwise, it may lead to unpredictable errors .
Be careful : It's not that your programming habits have gone wrong , It is Unity The problem of mechanism . If not inherited Monobehaviour Please be bold to initialize in the member declaration or constructor , therefore ……

terms of settlement :
use Awake() or Start() Instead of constructors !
use Awake() or Start() Instead of constructors !
use Awake() or Start() Instead of constructors !
perhaps
Don't inherit Monobehaviour!
Don't inherit Monobehaviour!
Don't inherit Monobehaviour!

Reference article link here

原网站

版权声明
本文为[God of Luo Xiu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101700200530.html