· 

【Unity】文章・URL・ハッシュタグ付きツイートリンクを生成する方法|X(旧Twitter)でポストシェアを促す際に最適!コード付きで初心者向けに解説【C#スクリプト】

個人開発者のブログ

Unity画像
今回は、ゲーム・アプリ内から文章・URL・ハッシュタグ付きツイートリンクを、簡単に生成する方法をコード付き(C#)で紹介します。
文章内にはゲーム内変数も組み込めるので、ぜひ活用しましょう!
*当記事はプロモーションも含みます。

目次

  1. 実際のコード

  2. エディター拡張コード

  3. まとめ
     


実際のコード

using System;
using System.Web; // 注意: Unityエディタでは using UnityEngine.Networking; を使うこともある
using UnityEngine;

public class TweetManager : MonoBehaviour
{
    public static TweetManager instance = null;

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else Destroy(this.gameObject);
    }

    /// <summary>
    /// ツイート用のURLリンクを生成します。
    /// </summary>
    public string GenerateTweetURL(string message, string url = "", string hashtag = "")
    {
        string fullText = message;

        if (!string.IsNullOrEmpty(url))
        {
            fullText += "\n" + url;
        }

        if (!string.IsNullOrEmpty(hashtag))
        {
            string[] tags = hashtag.Split(',');
            foreach (string tag in tags)
            {
                fullText += "\n#" + tag.Trim();
            }
        }

        string encodedText = Uri.EscapeDataString(fullText);

        return $"https://twitter.com/intent/tweet?text={encodedText}";
    }
}

▲上記が実際のコードです。
ハッシュタグは、「#」抜きの「,」区切りで必要分追加できます。

int data=100;
string tweetLink=GenerateTweetURL($"ツイート本文\nscore:{data}","https://本文に載せるリンク","タグ1,タグ2");

のように呼び出せばツイートリンクを取得できて、外部スクリプトから呼び出す場合は

string tweetLink=TweetManager.instance.GenerateTweetURL("ツイート本文","https://本文に載せる","タグ1,タグ2,タグ3");

で同様に取得可能です。

ただし、TweetManager.csをアタッチしたオブジェクトがシーン上にある前提なので、配置してからご活用ください。
ちなみに、改行コード\nと変数の使用も可能です。

エディター拡張コード

"どんな状況でも"、ツイートリンクを生成したい時とかあるかもしれません。
そんな時に便利なのが、カスタムウィンドウタイプのエディター拡張です。

using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections.Generic;
using System;

#if UNITY_EDITOR
public class PostLinkGenerator : EditorWindow
{
    private string postText = "";
    private string postLink = "";
    private string postTag = "";
    private string resultLog = "";
    private Vector2 scrollPos;

    [MenuItem("Tools/X post link generator")]
    public static void ShowWindow()
    {
        GetWindow<PostLinkGenerator>("PostLinkGenerator");
    }

    private void OnGUI()
    {
        GUILayout.Label("Xポストリンク生成ツール", EditorStyles.boldLabel);
        postText = EditorGUILayout.TextField("メインのポスト内容", postText);
        postLink = EditorGUILayout.TextField("掲載リンク", postLink);
        postTag = EditorGUILayout.TextField("付与タグ", postTag);

        if (GUILayout.Button("リンク生成"))
        {
            if (!string.IsNullOrEmpty(postText) && !string.IsNullOrEmpty(postLink) && !string.IsNullOrEmpty(postTag))
            {
                string fullText = postText;

                if (!string.IsNullOrEmpty(postLink))
                {
                    fullText += "\n" + postLink;
                }

                if (!string.IsNullOrEmpty(postTag))
                {
                    string[] tags = postTag.Split(',');
                    foreach (string tag in tags)
                    {
                        fullText += "\n#" + tag.Trim();
                    }
                }

                string encodedText = Uri.EscapeDataString(fullText);
                resultLog = $"https://twitter.com/intent/tweet?text={encodedText}";
            }
            else
            {
                EditorUtility.DisplayDialog("入力エラー", "全ての入力項目に入力してください。", "OK");
            }
        }

        GUILayout.Space(15);
        GUILayout.Label("生成結果ログ", EditorStyles.boldLabel);
        scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Height(200));
        EditorGUILayout.TextArea(resultLog, GUILayout.ExpandHeight(true));
        EditorGUILayout.EndScrollView();
    }
}
#else
public class PostLinkGenerator : MonoBehaviour
{
    void Start()
    {
        ;
    }
}
#endif

カスタムウィンドウ画面はこんな感じで▼

生成サンプル画像

Unity上部にある
【ツール>X post link generator】
から開くことができ、必要な入力後にリンク生成ボタンを押すだけで取得できます。

生成サンプル画像

リンク内容の結果はこの通りで、

当記事のコードをコピペするだけで済むので、初心者でも簡単に実現できます。

おすすめUnityアセット【PR】

まとめ

いかがでしたか?
今回紹介したコードをコピペするだけで、簡単にツイートリンクの生成ができます。
もし必要な際は、是非今回紹介したコードを活用してみて下さい。
 
ここまで記事を見て頂き、誠にありがとうございました。
これからも開発関連の記事は更新し続けるつもりなので、今後も機会があれば見てみてください。
では、また別の記事でお会いましょう。。_(:3 」∠)_🀄

アソシエイト画像

最新Unity開発記事まとめ

☟Unity開発に関する最新情報をチェックしよう!

アソシエイト画像

イラスト守るくん(Google Play)

☝絵師必見!AI無断学習対策アプリ