Unity利用系统自带ApI(DateTime)创建日历表

首先先上结果:

 

先介绍下结构:

Unity利用系统自带ApI(DateTime)创建日历表_第1张图片

Unity利用系统自带ApI(DateTime)创建日历表_第2张图片

 

 

下面上代码首先创建TimeManager脚本组件:

using System;
public class TimeManager
{  
  
    /// 
    /// 得到月份的天数
    /// 
    /// 年
    /// 月
    /// 
    public static int GetMouthDays(int year, int mouth)
    {
        return DateTime.DaysInMonth(year, mouth);
    }
    /// 
    /// 得到天数为礼拜几
    /// 
    /// 年
    /// 月
    /// 日
    /// 
    public static int GetDayOfWeek(int year, int mouth, int day)
    {

        DateTime dt = new DateTime(year, mouth, day);
      
        switch (dt.DayOfWeek.ToString())
        {
            case "Monday":return 1;
            case "Tuesday": return 2;
            case "Wednesday": return 3;
            case "Thursday": return 4;
            case "Friday": return 5;
            case "Saturday": return 6;
            case "Sunday": return 7;
        }
        return 0;
    }
  

}

接下来创建Createclander脚本可以挂在场景中的任何对象上:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;//引入命名空间
using UnityEngine.UI;
public class Createcalender : MonoBehaviour
{

    int int_NewYear;
    int int_NewMouth;
    int int_NewDay;
    [Header("日期")]
   
    public Text txt_ShowDayData;
    public Transform trans_parent;

    private Image curBtnImage;
    private Color curColor;

    void Start()
    {
        DateTime nowDateTime = DateTime.Now;     
        int_NewYear = nowDateTime.Year;
        int_NewMouth = nowDateTime.Month;
        int_NewDay = nowDateTime.Day;
        txt_ShowDayData.text = int_NewYear + "年" + int_NewMouth + "月" + int_NewDay + "号";
        ShowLeftDayList(int_NewYear, int_NewMouth, int_NewDay);//根据获取到的时间展示日历表
    }

    void ShowLeftDayList(int year, int mouth, int day)
    {
        ClearChildren(trans_parent);//
        txt_ShowDayData.text = year + "年" + mouth + "月" + day + "号";     
        GameObject itemTpl = Resources.Load("Prefabs/DayItem");

        int days = TimeManager.GetMouthDays(year, mouth);//这一年的这一个月有多少天
        int week = TimeManager.GetDayOfWeek(year, mouth, 1);//得到每月一号是星期几 

        for (int i = 1; i < week; i++)//从每月一号开始排列子物体,举个例子若某月一号是星期三,则把星期三前(即1号之前的)的背景图片去掉 但是仍要占据位置
        {
            GameObject go = InstantiateItemSetParent(itemTpl, trans_parent);//
            go.transform.localScale = Vector3.one;            
            go.transform.Find("txt").GetComponent().text = "";
            Destroy(go.transform.GetComponent());
        }

        for (int k = 1; k <= days; k++)//选择的那一个月有多少天,克隆出来几个子物体
        {
            GameObject go = InstantiateItemSetParent(itemTpl, trans_parent);
            go.transform.localScale = Vector3.one;
            int NewDay = k;
            go.transform.Find("txt").GetComponent().text = k + "";

            Button btn = go.GetComponent

Unity利用系统自带ApI(DateTime)创建日历表_第3张图片

当然了上面的两个脚本也可以合为一个脚本实现额。。。。 

你可能感兴趣的:(Unity封装工具)