Unity时间管理脚本更新循环未显示月末最后一天问题
问题描述
我在Unity中编写了如下作为「时间管理器」的C#脚本:
void Update() { timer -= Time.deltaTime; if (timer <= 0) { SetCurrentDay(currentDate.day.day++); if (currentDate.day.day >= currentDate.month.maxDays) { SetCurrentDay(0); SetCurrentMonth(currentDate.month.month++); } timer = minuteToRealTime; } }
目前该循环逻辑基本正常,但以1月为例,日期从1年1月1日开始循环,到1年1月30日后,并未显示当月maxDays对应的31日,直接跳转到1年2月1日;同理2月会跳过28日直接进入3月。请问如何修改代码,才能让日期显示月末最后一天后再切换月份?
解决方案
问题根源在于日期更新与月份切换的判断逻辑顺序错误:当日期递增到等于当月最大天数时,你的代码立刻触发了月份切换,导致最后一天还没展示就跳转到了下月。
修改后的代码(日期以1为起始,1对应当月第一天)
void Update() { timer -= Time.deltaTime; if (timer <= 0) { // 先递增日期并同步显示 currentDate.day.day++; SetCurrentDay(currentDate.day.day); // 仅当日期超过当月最大天数时,才切换月份 if (currentDate.day.day > currentDate.month.maxDays) { // 重置日期为当月第一天 currentDate.day.day = 1; SetCurrentDay(currentDate.day.day); // 递增并切换月份 currentDate.month.month++; SetCurrentMonth(currentDate.month.month); // 可在此补充年份切换逻辑(如需) // if (currentDate.month.month > 12) // { // currentDate.month.month = 1; // currentDate.year.year++; // SetCurrentYear(currentDate.year.year); // } } timer = minuteToRealTime; } }
如果你的日期以0为起始(0对应当月第一天)
调整判断条件即可,代码如下:
void Update() { timer -= Time.deltaTime; if (timer <= 0) { currentDate.day.day++; SetCurrentDay(currentDate.day.day); // 当日期等于当月最大天数时,重置并切换月份 if (currentDate.day.day == currentDate.month.maxDays) { currentDate.day.day = 0; SetCurrentDay(currentDate.day.day); currentDate.month.month++; SetCurrentMonth(currentDate.month.month); } timer = minuteToRealTime; } }
核心调整说明
- 先完成日期递增与显示操作,再判断是否需要切换月份,确保最后一天能正常展示
- 针对不同的日期起始规则(1或0起始),调整判断条件与重置值,保证逻辑匹配
内容的提问来源于stack exchange,提问作者JamieRhys
相关产品推荐
相关产品推荐

