1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Unity]シンプルな期間限定機能作成(DateTimeの利用メモー)

Last updated at Posted at 2019-01-11

クライアントのみでの処理

TimeLimit.csコンポネント作成

public class TimeLimit : MonoBehaviour
{
    /// <summary>
    /// 限定日にち
    /// </summary>
    [SerializeField]
    private LimitedTime limitedtime;
    [SerializeField]
    private GameObject description;
    private void Start()
    {
        //起動時、期間内時チェック
        if (PlayerPrefs.GetString("HasExpired", "false") == "false")
        {
            //期間切れ処理
            if (HasExpired(limitedtime))
                PlayerPrefs.SetString("HasExpired", "true");
        }
        //期間切れ処理
        if (PlayerPrefs.GetString("HasExpired", "false") == "true")
            description.SetActive(true);
        //期間内処理
        else
            SceneManager.LoadScene("Main");
    }
    /// <summary>
    /// 期間切れかどうかを返す
    /// true:期間切れ、false:期間内
    /// </summary>
    private bool HasExpired(LimitedTime limit)
    {
        //現在の UTC 日時
        var now = DateTime.UtcNow;
        //限定日時取得
        var limitdate = GetDateTime(limit);
        //残り日時処理
        var remaining = limitdate - now;
        //残り日数チェック
        if (remaining.TotalDays < 0)
            return true;
        return false;
    }
    /// <summary>
    /// DateTimeを返す
    /// 日にち範囲外の処理をする。
    /// </summary>
    private DateTime GetDateTime(LimitedTime limit){
        //limit.year年範囲外処理
        var year = Mathf.Clamp(limit.year, 2018, 2028);
        //limit.month月範囲外処理
        var month = Mathf.Clamp(limit.month, 1, 12);
        //limit.month月の日数を取得
        var days = DateTime.DaysInMonth(year, month);
        //日範囲外処理
        var day = Mathf.Clamp(limit.day, 1, days);
        return new DateTime(year, month, day);
    }
}
[Serializable]
public class LimitedTime
{
    [Range(2019, 2028)]
    public int year;
    [Range(1, 12)]
    public int month;
    [Range(1, 31)]
    public int day;
}

シーン上GameObject作成し、TimeLimitコンポネントを追加しYear/Month/Dayを指定。
Descriptionには表示させるGameObjectをアタッチ
1.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?