Skip to content

Instantly share code, notes, and snippets.

@Kroporo
Created February 27, 2023 13:41
Show Gist options
  • Select an option

  • Save Kroporo/af136f85df7a83209835b281e7178b89 to your computer and use it in GitHub Desktop.

Select an option

Save Kroporo/af136f85df7a83209835b281e7178b89 to your computer and use it in GitHub Desktop.
This gets the word of the day and writes it into a few Text boxes. It's designed to be a small gimmick, though due to licensing with Dictionary.com... This can not be used in any commercial product 💤
using System;
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
public class WordDefinitionText : MonoBehaviour {
public TMP_Text wordText;
public TMP_Text typeText;
public TMP_Text definitionText;
protected IEnumerator Start() {
// Fetch word of the day if the cached word is outdated
if (PlayerPrefs.GetInt("wotd_last_update", 0) != (int) Math.Floor(new TimeSpan(DateTime.UtcNow.Ticks).TotalDays)) {
yield return FetchWord();
}
// Apply cached word of the day
wordText.text = PlayerPrefs.GetString("wotd_word");
typeText.text = PlayerPrefs.GetString("wotd_type");
definitionText.text = PlayerPrefs.GetString("wotd_definition");
}
private IEnumerator FetchWord() {
UnityWebRequest www = UnityWebRequest.Get("https://www.dictionary.com/e/word-of-the-day/");
var operation = www.SendWebRequest();
yield return operation;
try {
if (operation.webRequest.result != UnityWebRequest.Result.Success) {
throw new Exception("Failed to fetch word of the day: " + operation.webRequest.error);
}
var text = operation.webRequest.downloadHandler.text;
int wordStart = text.IndexOf("<h1 class=\"js-fit-text\" style=\"color: #0046BE\">") + 47;
int wordEnd = text.IndexOf("</h1>", wordStart);
int typeStart = text.IndexOf("<span class=\"luna-pos\">") + 23;
int typeEnd = text.IndexOf("</span>", typeStart);
int definitionStart = text.IndexOf("<p>", typeEnd) + 3;
int definitionEnd = text.IndexOf("</p>", definitionStart);
PlayerPrefs.SetString("wotd_word", text[wordStart..wordEnd]);
PlayerPrefs.SetString("wotd_type", text[typeStart..typeEnd]);
PlayerPrefs.SetString("wotd_definition", text[definitionStart..definitionEnd]);
} catch (Exception e) {
Debug.LogException(e);
PlayerPrefs.SetString("wotd_word", "Error");
PlayerPrefs.SetString("wotd_type", "Noun");
PlayerPrefs.SetString("wotd_definition", "a deviation from accuracy or correctness; a mistake, as in action or speech");
}
PlayerPrefs.SetInt("wotd_last_update", (int) Math.Floor(new TimeSpan(DateTime.UtcNow.Ticks).TotalDays));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment