当前位置:网站首页>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!
边栏推荐
- 蓝桥杯_糊涂人寄信_递归
- CUDA realizes efficient search - failed audit?
- 小程序积分商城如何实现营销目的
- Leetcode 875. Coco, who likes bananas
- LeetCode 255. 验证前序遍历序列二叉搜索树*
- Leetcode 875. 爱吃香蕉的珂珂
- 苹果期待的「无密码时代」,真能实现吗?
- Lifeifei: I am more like a scientist in physics than an engineer
- When V-IF and V-for need to be used at the same time
- 第七部分:第二课 顾问通用技能-如何安装和卸载SAP ERP系统客户端
猜你喜欢
随机推荐
Talk about message oriented middleware (1) and AMQP
项目中常用的19条MySQL优化
js锚点定位可以扩展很多功能
OpenJudge NOI 1.13 15:求序列中的众数
IIS安装 部署网站
为什么 0.1+0.2=0.30000000000000004
Nacos配置管理
Summary of vim common commands
嘿!ONES 新星请看过来|师兄师姐说
安全感
Redis通用指令
基于业务沉淀组件 => manage-table
LeetCode 255. 验证前序遍历序列二叉搜索树*
Leetcode 321. Nombre maximum de raccords
pands pd. Detailed parsing of dataframe() function
LeetCode 321. Maximum number of splices***
Leetcode String to integer(Atoi)
mmdetection之dataloader构建
Photoshop如何打开、编辑和导出Webp格式图片的方法
Classic topics of leetcode tree (I)









