Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

First, the effect drawing

Unsigned version:


Second, the idea of production

Use the way of changing the background color of the picture to change the state [gray: signed in; blue: available; white: not signed in]

Main logic:

  • Every time you sign in, save a sign in date to judge whether you sign in today.
  • Display UI interface and prompt information according to whether you have signed in;
  • If you do not sign in, click the button to sign in (save the date of signing in, issue rewards, maintain UI display, etc.);
  • There is also a logic reset for the start of the check-in week;

The above logic, basically simulated the king of Glory check-in panel function, let’s start to implement it.


Third, scene construction

The Demo scenario is as shown above :(a little ugly without resources ~)

  1. Make a sign in button (Image, Image and Text below)
  2. Make six copies (create a separate empty object as their parent)
  3. Create a text (put it anywhere to display a prompt)

Four, code implementation

Is according to the logic of the implementation of the above, the code notes are also written in detail, all the code is as follows:

using System;
using UnityEngine;
using UnityEngine.UI;

public class SingInDemo : MonoBehaviour
{
	// The parent of the check-in button
    public Transform WeekParent;
    
    // Prompt text
    public Text HintText;
    
    // Last check-in time -- compare with today's time to determine whether you have checked in today
    private readonly string prefsLastCheckTime = "prefsLastCheckTime";
    
    // How many days have you checked in this week example: 2 --> Indicates that you checked in on Monday and Tuesday
    private readonly string prefsWeekAlreadyDay = "prefsWeekAlreadyDay";

    What day is it today
    private int weekToday;
    // I checked in several days this week
    private int alreadyDay;

    void Start()
    {
        //PlayerPrefs.DeleteAll();
        weekToday = GetDateWeek(DateTime.Now.ToString());

        AlreadyByWeek();
        // Check how many days you have checked in this week
        alreadyDay = PlayerPrefs.GetInt(prefsWeekAlreadyDay);

        for (int i = 0; i < WeekParent.childCount; i++)
        {
            GameObject go = WeekParent.GetChild(i).gameObject;
            // Listen for button clicks
            go.GetComponent<Button>().onClick.AddListener(() => { OnClickSingInBtn(go); });

            // Indicates whether you have checked in
            bool isAlready = alreadyDay > i;
            go.GetComponent<Image>().color = isAlready ? Color.gray : Color.white;
            go.transform.GetChild(1).gameObject.SetActive(isAlready);
        }

        // I haven't checked in yet
        if(! AlreadyByToDay()) { WeekParent.GetChild(alreadyDay).GetComponent<Image>().color = Color.cyan; }// Displays a prompt message
        ShowHintText(alreadyDay);
    }

    // Click the check-in button
    private void OnClickSingInBtn(GameObject go)
    {
        // What time is it? Sign in button
        string week = go.name.Split('_') [1];
        Debug.Log("Clicked..." + go.name + "Button, it's zhou." + week);

        / / to sign in
        alreadyDay = PlayerPrefs.GetInt(prefsWeekAlreadyDay);
        if(! AlreadyByToDay()) { Debug.Log("Check in, check in, check in, yes Chow." + week);
            go.transform.GetChild(1).gameObject.SetActive(true);
            go.transform.GetComponent<Image>().color = Color.gray;
            PlayerPrefs.SetString(prefsLastCheckTime, DateTime.Now.ToString("d"));
            PlayerPrefs.SetInt(prefsWeekAlreadyDay, ++alreadyDay);

            // Displays a prompt message
            ShowHintText(alreadyDay);
            Debug.Log("~~~~~~~~~~~~ the reward for successful check-in has not been written yet ~~~~~~~~~~~~");
        }
        else
        {
            Debug.Log("I have already signed in today. I can't sign in again."); }}/// <summary>
    ///Check in this week - calculate whether the last check in was within this week
    /// </summary>
    void AlreadyByWeek()
    {
        if(! PlayerPrefs.HasKey(prefsLastCheckTime))return;
        
        // This week is Monday
        string startWeek = GetMondayDate(DateTime.Now).ToString("d");
        // Last check-in time was Monday
        DateTime dtmE = DateTime.Parse(PlayerPrefs.GetString(PlayerKey.SigninLastCheckTime.ToString()));
        string lastWeek =  GetMondayDate(dtmE).ToString("d");

        // Last check-in week was not this week && No check-in today
        if(startWeek ! = lastWeek && ! AlreadyByToDay()) { Debug.Log("New week begins, reset all check-in information..."); PlayerPrefs.DeleteKey(prefsLastCheckTime); PlayerPrefs.DeleteKey(prefsWeekAlreadyDay); }}/// <summary>
    ///Have you checked in today
    /// </summary>
    /// <returns></returns>
    bool AlreadyByToDay()
    {
        string today = DateTime.Now.ToString("d");
        return PlayerPrefs.GetString(prefsLastCheckTime) == today;
    }
    
    /// <summary>
    ///Returns the day of the week of the incoming date
    /// </summary>
    /// <param name="strYMD"></param>
    /// <returns></returns>
    int GetDateWeek(string strYMD)
    {
        int week = Convert.ToInt32(Convert.ToDateTime(strYMD).DayOfWeek);
        // 0: Indicates Sunday
        returnweek ! =0 ? week : 7;
    }

    // Prompt text
    void ShowHintText(int alreadyDay)
    {
        if(! AlreadyByToDay()) { HintText.text ="Not checked in today, checked in this week." + alreadyDay + "Day";
        }
        else
        {
            HintText.text = "Signed today, signed this week:" + alreadyDay + "Oh, my God, you can sign it." +  (weekToday - alreadyDay) + "Day";; }}/// <summary>
    ///Calculate the start date of a day (Monday date)
    /// </summary>
    /// <param name="someDate">Any day of the week</param>
    /// <returns>Returns the Monday date followed by hours, minutes, and seconds equal to the value passed in</returns>
    DateTime GetMondayDate(DateTime someDate)
    {
        int i = someDate.DayOfWeek - DayOfWeek.Monday;
        if (i == - 1) i = 6;// I > = 0, Sunday = 0, Sunday =-1, +7=6
        TimeSpan ts = new TimeSpan(i, 0.0.0);
        returnsomeDate.Subtract(ts); }}Copy the code

Fifth, expand the supplementary version

Following the above implementation idea, it is very easy to implement a backsigned version:

Take a look at the rendering: It’s just checking the above codeHave you checked in todayIs changed toCan I have it resigned, and then add a countersign logic.

Scene building is the same as above, the code implementation is as follows:

using System;
using UnityEngine;
using UnityEngine.UI;

public class SingInDemo : MonoBehaviour
{
    // The parent of the check-in button
    public Transform WeekParent;
    
    // Prompt text
    public Text HintText;
    
    // Last check-in time -- compare with today's time to determine whether you have checked in today
    private readonly string prefsLastCheckTime = "prefsLastCheckTime";
    
    // How many days have you checked in this week example: 2 --> Indicates that you checked in on Monday and Tuesday
    private readonly string prefsWeekAlreadyDay = "prefsWeekAlreadyDay";

    What day is it today
    private int weekToday;
    // I checked in several days this week
    private int alreadyDay;

    void Start()
    {
        //PlayerPrefs.DeleteAll();
        weekToday = GetDateWeek(DateTime.Now.ToString());

        AlreadyByWeek();
        // Check how many days you have checked in this week
        alreadyDay = PlayerPrefs.GetInt(prefsWeekAlreadyDay);

        for (int i = 0; i < WeekParent.childCount; i++)
        {
            GameObject go = WeekParent.GetChild(i).gameObject;
            // Listen for button clicks
            go.GetComponent<Button>().onClick.AddListener(() => { OnClickSingInBtn(go); });

            // Indicates whether you have checked in
            bool isAlready = alreadyDay > i;
            go.GetComponent<Image>().color = isAlready ? Color.gray : Color.white;
            go.transform.GetChild(1).gameObject.SetActive(isAlready);
        }

        // I haven't checked in yet
        if (weekToday - alreadyDay > 0)  / / (! AlreadyByToDay()) // todo... It is not allowed to be re-signed
        {
            WeekParent.GetChild(alreadyDay).GetComponent<Image>().color = Color.cyan;
        }

        // Displays a prompt message
        ShowHintText(alreadyDay);
    }

    // Click the check-in button
    private void OnClickSingInBtn(GameObject go)
    {
        // What time is it? Sign in button
        string week = go.name.Split('_') [1];
        Debug.Log("Clicked..." + go.name + "Button, it's zhou." + week);

        / / to sign in
        alreadyDay = PlayerPrefs.GetInt(prefsWeekAlreadyDay);
        if (weekToday - alreadyDay > 0)  / / (! AlreadyByToDay()) // todo... It is not allowed to be re-signed
        {
            Debug.Log("Check in, check in, check in, yes Chow." + week);
            go.transform.GetChild(1).gameObject.SetActive(true);
            go.transform.GetComponent<Image>().color = Color.gray;
            PlayerPrefs.SetString(prefsLastCheckTime, DateTime.Now.ToString("d"));
            PlayerPrefs.SetInt(prefsWeekAlreadyDay, ++alreadyDay);

            // Displays a prompt message
            ShowHintText(alreadyDay);

            #regionComplementary logic -- Todo.. Do not need to re-sign directly delete
            if (AlreadyByToDay())
            {
                Debug.Log("-- Signed successfully, this is the week's number" + alreadyDay + "Second check-in --");
            }
            else
            {
                Debug.Log("+++ check-in success. That's number one this week." + alreadyDay + "Second check-in +++");
            }

            // Add clickable logo
            if (weekToday - alreadyDay > 0)
            {
                WeekParent.GetChild(alreadyDay).GetComponent<Image>().color = Color.cyan;
            }
            #endregion
            
            Debug.Log("~~~~~~~~~~~~ the reward for successful check-in has not been written yet ~~~~~~~~~~~~");
        }
        else
        {
            Debug.Log("I have already signed in today. I can't sign in again."); }}/// <summary>
    ///Check in this week - calculate whether the last check in was within this week
    /// </summary>
    void AlreadyByWeek()
    {
        if(! PlayerPrefs.HasKey(prefsLastCheckTime))return;
        
       // This week is Monday
        string startWeek = GetMondayDate(DateTime.Now).ToString("d");
        // Last check-in time was Monday
        DateTime dtmE = DateTime.Parse(PlayerPrefs.GetString(PlayerKey.SigninLastCheckTime.ToString()));
        string lastWeek =  GetMondayDate(dtmE).ToString("d");

        // Last check-in week was not this week && No check-in today
        if(startWeek ! = lastWeek && ! AlreadyByToDay()) { Debug.Log("New week begins, reset all check-in information..."); PlayerPrefs.DeleteKey(prefsLastCheckTime); PlayerPrefs.DeleteKey(prefsWeekAlreadyDay); }}/// <summary>
    ///Have you checked in today
    /// </summary>
    /// <returns></returns>
    bool AlreadyByToDay()
    {
        string today = DateTime.Now.ToString("d");
        return PlayerPrefs.GetString(prefsLastCheckTime) == today;
    }
    
    /// <summary>
    ///Returns the day of the week of the incoming date
    /// </summary>
    /// <param name="strYMD"></param>
    /// <returns></returns>
    int GetDateWeek(string strYMD)
    {
        int week = Convert.ToInt32(Convert.ToDateTime(strYMD).DayOfWeek);
        // 0: Indicates Sunday
        returnweek ! =0 ? week : 7;
    }

    // Prompt text
    void ShowHintText(int alreadyDay)
    {
        if(! AlreadyByToDay()) { HintText.text ="Not checked in today, checked in this week." + alreadyDay + "Day";
        }
        else
        {
            HintText.text = "Signed today, signed this week:" + alreadyDay + "Oh, my God, you can sign it." +  (weekToday - alreadyDay) + "Day";; }}/// <summary>
    ///Calculate the start date of a day (Monday date)
    /// </summary>
    /// <param name="someDate">Any day of the week</param>
    /// <returns>Returns the Monday date followed by hours, minutes, and seconds equal to the value passed in</returns>
    DateTime GetMondayDate(DateTime someDate)
    {
        int i = someDate.DayOfWeek - DayOfWeek.Monday;
        if (i == - 1) i = 6;// I > = 0, Sunday = 0, Sunday =-1, +7=6
        TimeSpan ts = new TimeSpan(i, 0.0.0);
        returnsomeDate.Subtract(ts); }}Copy the code

If you still don’t understand the place, you can comment on the consultation, or click on the link to see the sample source: source link