MR and Azure 301 Academyをやってみた

Academy

はまったポイント

<html><body><h1>Argument Exception</h1><p>Method: Translate()</p><p>Parameter: </p><p>Message: The received token is of incorrect token type.</p><code></code><p>message id=1446.V2_Rest.Translate.41CDCE1B</p></body></html>
UnityEngine.Debug:Log(Object)
<TranslateWithUnityNetworking>c__Iterator1:MoveNext() (at Assets/Scripts/Translator.cs:144)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

tokenをDebugで表示すると、こんなものが。
何度やっても翻訳できなかった原因はこれでした。
Tokenがおかしいらしい

Translorクラスの TranslateWithUnityNetworking メソッド

unityWebRequest.SetRequestHeader("Authorization", "Bearer " + authorizationToken);

ここ。
しっかり文章をコピーしてペーストした場合は、大丈夫。 写経をするときは気を付けてください。
Bearer の後ろは半角スペースが入ってます。
明示的に半角スペースを結合してくれた方がわかりやすいのに。。。


ここからは和訳メモ。

申し訳ないですがきっと役に立ちません

↓ただの和訳メモ見たいな感じ

docs.microsoft.com

こんな素晴らしいものが追加されたので、 やってみました。 メモを取りながら書いて、もう投稿します。

Language Translation

AzureのCognitiveServicesを使う
TranslatorTextAPI

Translator Text APIはほぼリアルタイムで動く翻訳サービス RESTAPIを使っている クラウドベース

https://azure.microsoft.com/en-us/services/cognitive-services/translator-text-api/ 詳しくはここ

コースが終わったら、次のようなことが可能なMRアプリが出来ている 1. ユーザーはマイクに向かって話しかけられる(HoloLens or immersive headset) 2. 話し言葉を捕らえ、Azure Translator Text APIに送ります 3. 翻訳結果がUnityシーンのシンプルなUI上に表示されます

DeviceSupport - HoloLens - Immersive headsets

Note

Prerequsites(前提)

  • WinMR対応のPC
  • FallCreatorsUpdate(バージョンは1709)
  • Windows10April2018UpdateSDK
    • ダウンロードした
  • 2017.4.1f1
    • 4.3f1を選択
    • 多分上位互換のはず

Before you start

  • プロジェクトをビルドするときに問題がないように、ルート パスかもしくは近いところにプロジェクトを作成すること!
    • 長い名前のパスは失敗する恐れあり
  • このコードは、PCに接続してあるデフォルトのマイクから音声を録音することを許可する
    • マイクがセットされていることを確認してください
  • ディクテーションをするためにPCの設定を変える
    • Settings > Privacy > Speech, inking & typing
    • 設定 > プライバシー > 音声認識、手書き入力、入力の設定
    • Turn On speech services and typing suggestions
    • 音声認識サービスと入力候補をオフにします
  • もしヘッドセットについているマイクを使いたい場合
    • If you're using a microphone and headphones connected to (or built-in to) your headset, make sure the option “When I wear my headset, switch to headset mic” is turned on in Settings > Mixed reality > Audio and speech.

chapter1 AzurePortal

Azureを使うためにサービスのインスタンスを設定する必要がある

  1. Azure Portalにログイン(https://portal.azure.com/)
  2. リソースの作成をクリック、translator text API を検索
    1. Translator Speech Apiもあるので注意
  3. ↓の作成ボタンを押す
    1. もしかするとAzureサブスクリプションの取得という画面が出るかもしれない

リソースに移動を押す

Azure環境を整えるのに時間を費やしてしまった。。。

chapter2 Set up the Unity project

やっとヘッドセットの出番 モーションコントローラーはいらない

rootプロジェクトに近いとこにプロジェクトを作る

Edit > Preferences External Tools. vs2017なのを確認

File > Build SettingsからUniversal Windows Platformにswitch the platformをクリック

Target Device is set to Any Device. - For Microsoft HoloLens, set Target Device to HoloLens.

Build Type is set to D3D

SDK is set to Latest installed

Visual Studio Version is set to Latest installed

Build and Run is set to Local Machine

Save the scene and add it to the build.

Do this by selecting Add Open Scenes. A save window will appear.

UWPがUnityに入ってなくて、ダウンロードページになった METROセットアップ 無理

↓もしかしたら要らないかも。。。 書いてないけど、Unityダウンロードするときに、 コンポーネントで二つ追加する必要あり

In the Other Settings tab:

Scripting Runtime VersionをStable (.NET 3.5 Equivalent).

Scripting Backendを.NET

API Compatibility Levelを.NET 4.6

Within the Publishing Settings tab, under Capabilities, check:

InternetClient

Microphone

Further down the panel, in XR Settings (found below Publish Settings), tick Virtual Reality Supported, make sure the Windows mixed reality SDK is added

build settingsでC#選択

Chapter 3 – Main Camera setup

unityパッケージをダウンロードして、チャプター5からやってもいいよ

  1. MainCameraというのは、アプリケーションを起動したときの頭になる
  2. コンポーネントの確認
  3. MainCamera>Transformのギアアイコンをクリック>Reset
  4. Transformは、Position is set to 0, 0, 0Rotation is set to 0, 0, 0Scale is set to 1, 1, 1になっているはず
  5. MainCamera>AddComponent
  6. Audio Sourceをタイプしてクリック

注意:HoloLensには - ClearFlags>SolidColor - Background>black, alpha 0(RGBA全て0にする)

Chapter 4 – Setup Debug Canvas

翻訳のインプットとアウトプットを見るために、基本的なUIが必要

ここではCanavasUIオブジェクトを作りテキストデータを見る

  1. Hierarchyの何もないところで右クリック(本当に何もないところにする) UI>Canvasを選択
  2. Canvas>CanvasコンポーネントのRenderModeをWorldSpaceに
  3. RectTransformを
  4. POS - X 0 Y 0 Z 40
  5. Width - 500
  6. Height - 300
  7. Scale - X 0.13 Y 0.13 Z 0.13 に変更

  8. ヒエラルキーCanvasを右クリックしUI>Panelをクリック このパネルはテキストの背景にする予定

  9. Panelを右クリック>UI>Textこれを4回行う(ctrl + Dでコピーできる)

  10. 次のように変更 このときパラメータにかなり共通点があるので一つ変更してからコピーしてやることをおすすめする
Rect Transform component:
Name    Transform - Position    Width   Height
MicrophoneStatusLabel   X -80 Y 90 Z 0  300 30
AzureResponseLabel  X -80 Y 30 Z 0  300 30
DictationLabel  X -80 Y -30 Z 0 300 30
TranslationResultLabel  X -80 Y -90 Z 0 300 30

Text (Script) component:
Name    Text    Font Size
MicrophoneStatusLabel   Microphone Status:  20
AzureResponseLabel  Azure Web Response  20
DictationLabel  You just said:  20
TranslationResultLabel  Translation:    20

FontスタイルをBoldにする
読みやすくなる
  1. 作った全てのテキストオブジェクトに、右クリックでUI>Text

@ 8と9をやるときのおすすめとして、ctrl + クリックで変更したいオブジェクトを一斉選択 これですべてのオブジェクトのパラメーターの変更が可能

  1. また次のように
Rect Transform component:

Name    Transform - Position    Width   Height
MicrophoneStatusText    X 0 Y -30 Z 0   300 30
AzureResponseText       X 0 Y -30 Z 0   300 30
DictationText           X 0 Y -30 Z 0   300 30
TranslationResultText   X 0 Y -30 Z 0   300 30

Text (Script) component:

Name    Text    Font Size
MicrophoneStatusText    ??  20
AzureResponseText   ??  20
DictationText   ??  20
TranslationResultText   ??  20
  1. elect the 'centre' alignment option for each text component:

  2. 子供のほうのUIテキストで色を変更、Colorをクリック

  3. Hex Color to: 0032EAFF
  4. 子供のテキストのほうは青くなるはず

Chapter 5 – Create the Results class

Resultsクラスを作成 翻訳の結果を見るためのクラス - Azureからの返り値 - マイクのステータス - ディクテーション結果 - 翻訳結果 これらを保持

  1. Project Panelで右クリック、Create>Folder、名前はScripts
  2. ダブルクリックでまたCreate>C#Script、名前はResults
  3. ResultsをダブルクリックでVisualStudioが立ち上がる
  4. ネームスペースの追加
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
  1. クラス内部で変数を追加
public static Results instance;

[HideInInspector] 
public string azureResponseCode;

[HideInInspector] 
public string translationResult;

[HideInInspector] 
public string dictationResult;

[HideInInspector] 
public string micStatus;

public Text microphoneStatusText;

public Text azureResponseText;

public Text dictationText;

public Text translationResultText;
  1. Awakeメソッドを追加、これはクラスイニシャライズの際に呼ばれる
private void Awake() 
{ 
    // Set this class to behave similar to singleton 
    instance = this;           
} 
  1. 最後に、アウトプットするためのメソッドを書く これは様々な結果情報をUIに出力する
/// <summary>
/// Stores the Azure response value in the static instance of Result class.
/// </summary>
public void SetAzureResponse(string result)
{
    azureResponseCode = result;
    azureResponseText.text = azureResponseCode;
}

/// <summary>
/// Stores the translated result from dictation in the static instance of Result class. 
/// </summary>
public void SetDictationResult(string result)
{
    dictationResult = result;
    dictationText.text = dictationResult;
}

/// <summary>
/// Stores the translated result from Azure Service in the static instance of Result class. 
/// </summary>
public void SetTranslatedResult(string result)
{
    translationResult = result;
    translationResultText.text = translationResult;
}

/// <summary>
/// Stores the status of the Microphone in the static instance of Result class. 
/// </summary>
public void SetMicrophoneStatus(string result)
{
    micStatus = result;
    microphoneStatusText.text = micStatus;
}
  1. しっかり保存しよう(ctrl + s)

Chapter 6 – Create the MicrophoneManager class

二つ目のクラスはMicrophoneManagerクラス これは: - マイクデバイスの検出 - audioを捉え、ディクテーションして、文字情報として保存する - 声が止まったら、Translator(翻訳)クラスへディクテーションを送信する - ボイスのキャプチャーを停止するメソッドも保持

1-3までは上と一緒でクラスを作成する 4. namespace

using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
using UnityEngine.Windows.Speech;
  1. variable
// Help to access instance of this object 
public static MicrophoneManager instance; 

// Recording frequency of mic 
private int frequency = 44100; 

// AudioSource component, provides access to mic 
private AudioSource audioSource; 

// Flag indicating mic detection 
private bool microphoneDetected; 

// Flag indicating audio capture status 
private bool isCapturingAudio;  

// Component converting speech to text 
private DictationRecognizer dictationRecognizer; 
  1. 初期化時に呼ばれるメソッド追加
private void Awake() 
{ 
    // Set this class to behave similar to singleton 
    instance = this; 
} 

void Start() 
{ 
    //Use Unity Microphone class to detect devices and setup Audiosource 
    if(Microphone.devices.Length > 0) 
    { 
        Results.instance.SetMicrophoneStatus("Initialising..."); 
        audioSource = GetComponent<AudioSource>(); 
        microphoneDetected = true; 
    } 
    else 
    { 
        Results.instance.SetMicrophoneStatus("No Microphone detected"); 
    } 
} 
  1. Updateは使わないので消去
  2. ボイスの録音を止めたり開始したり、Translatorクラスに渡すメソッドを追加 Start()メソッドの下に追加(どこでもいいのでは??)
/// <summary> 
/// Start microphone capture. Debugging message is delivered to the Results class. 
/// </summary> 
public void StartCapturingAudio() 
{ 
    if(microphoneDetected) 
    { 
        // Start microphone capture 
        isCapturingAudio = true;              
        
        // Start dictation 
        dictationRecognizer = new DictationRecognizer(); 
        dictationRecognizer.DictationResult += DictationRecognizer_DictationResult; 
        dictationRecognizer.Start(); 

        // Update UI with mic status 
        Results.instance.SetMicrophoneStatus("Capturing..."); 
    }      
} 

/// <summary> 
/// Stop microphone capture. Debugging message is delivered to the Results class. 
/// </summary> 
public void StopCapturingAudio() 
{ 
    Results.instance.SetMicrophoneStatus("Mic sleeping"); 
    isCapturingAudio = false; 
    Microphone.End(null); 
    dictationRecognizer.DictationResult -= DictationRecognizer_DictationResult; 
    dictationRecognizer.Dispose(); 
}
  1. 声が止まった時にinvoke(呼び出)されるDictation Handlerが必要 このメソッドはディクテーションされたテキストをTranslatorクラスに渡す
/// <summary>
/// This handler is called every time the Dictation detects a pause in the speech. 
/// Debugging message is delivered to the Results class.
/// </summary>
private void DictationRecognizer_DictationResult(string text, ConfidenceLevel confidence)
{
    // Update UI with dictation captured
    Results.instance.SetDictationResult(text);

    // Start the coroutine that process the dictation through Azure 
    StartCoroutine(Translator.instance.TranslateWithUnityNetworking(text));   
}

注意:エラーが出ているが大丈夫です Translatorクラスを参照しているが、まだ作ってないのです

Chapter 7 – Call to Azure and translator service

Chapter7

以下を担当するTranslatorクラスを作る - AuthTokenの代わりに、Azureの認証を行う - AuthTokenを使ってテキスト(MicrophoneManagerから受け取った)を送信する - 翻訳結果を受け取り、ResultClassに渡す

クラスを作るために: 1-3. Translatorクラスを今までと同じやり方で作る 4. namespaceの追加

using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.IO; 
using System.Net; 
using System.Net.Security; 
using System.Runtime.Serialization; 
using System.Xml; 
using UnityEngine; 
using UnityEngine.Networking;
  1. 変数の追加
public static Translator instance; 
private string translationTokenEndpoint = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken"; 
private string translationTextEndpoint = "https://api.microsofttranslator.com/v2/http.svc/Translate?"; 
private const string ocpApimSubscriptionKeyHeader = "Ocp-Apim-Subscription-Key"; 

//Substitute the value of authorizationKey with your own Key 
private const string authorizationKey = "-InsertYourAuthKeyHere-"; 
private string authorizationToken; 

// languages set below are: 
// English 
// French 
// Italian 
// Japanese 
// Korean 
public enum Languages { en, fr, it, ja, ko }; 
public Languages from = Languages.en; 
public Languages to = Languages.it;

Note - 上のenum languagesはただの例です。もし望むなら自由に追加して!60以上の言語をサポート! - authorizationKeyの値は、chapter1で自分で控えたキーに変更すること

  1. Awake()とStart()が必要
  2. このコードはauthorizationKeyを使ってtokenを手に入れる
private void Awake() 
{ 
    // Set this class to behave similar to singleton  
    instance = this; 
} 

// Use this for initialization  
void Start() 
{ 
    // When the application starts, request an auth token 
    StartCoroutine("GetTokenCoroutine", authorizationKey); 
}

Note: 10分後トークンは切れます
アプリのシナリオによっては、同じコルーチンを使って何回も呼ぶ必要があります

  1. トークンを取得するコルーチン
/// <summary> 
/// Request a Token from Azure Translation Service by providing the access key. 
/// Debugging result is delivered to the Results class. 
/// </summary> 
private IEnumerator GetTokenCoroutine(string key) 
{ 
    if (string.IsNullOrEmpty(key)) 
    { 
        throw new InvalidOperationException("Authorization key not set."); 
    } 

    WWWForm webForm = new WWWForm();

    using (UnityWebRequest unityWebRequest = UnityWebRequest.Post(translationTokenEndpoint, webForm)) 
    { 
        unityWebRequest.SetRequestHeader("Ocp-Apim-Subscription-Key", key);

        // The download handler is responsible for bringing back the token after the request 
        unityWebRequest.downloadHandler = new DownloadHandlerBuffer(); 

        yield return unityWebRequest.SendWebRequest(); 

        authorizationToken = unityWebRequest.downloadHandler.text; 

        if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError) 
        { 
            Results.instance.azureResponseText.text = unityWebRequest.error; 
        } 

        long responseCode = unityWebRequest.responseCode; 

        // Update the UI with the response code 
        Results.instance.SetAzureResponse(responseCode.ToString()); 
    } 

    // After receiving the token, begin capturing Audio with the MicrophoneManager Class 
    MicrophoneManager.instance.StartCapturingAudio(); 

    StopCoroutine("GetTokenCoroutine"); 

    yield return null; 
}
  1. 次にコルーチンを追加、これはMicrophoneManagerクラスから翻訳されたテキストを受け取る。 このコードはAzureAPIに送信するクエリ文字列を作り、Unity内部のUnityWebRequestを使い、クエリ文字列でエンドポイントにGetコールをする
    結果はResultsオブジェクトにセットされる
/// <summary> 
/// Request a translation from Azure Translation Service by providing a string.  
/// Debugging result is delivered to the Results class. 
/// </summary> 
public IEnumerator TranslateWithUnityNetworking(string text) 
{ 
    WWWForm webForm = new WWWForm(); 
    string result; 
    string queryString; 

    // This query string will contain the parameters for the translation 
    queryString = string.Concat("text=", Uri.EscapeDataString(text), "&from=", from, "&to=",to);        

    using (UnityWebRequest unityWebRequest = 
    UnityWebRequest.Get(translationTextEndpoint + queryString))        
    { 
        unityWebRequest.downloadHandler = new DownloadHandlerBuffer(); 
        unityWebRequest.SetRequestHeader("Authorization", "Bearer " + authorizationToken); 
        unityWebRequest.SetRequestHeader("Accept", "application/xml"); 
        yield return unityWebRequest.SendWebRequest(); 

        string deliveredString = unityWebRequest.downloadHandler.text; 

        // The response will be in Json format 
        // Therefore we need to deserialise it 
        DataContractSerializer serializer; 
        serializer = new DataContractSerializer(typeof(string)); 
        using (Stream stream = GenerateStreamFromString(deliveredString)) 
        { 
            // Set the UI with the translation 
            Results.instance.SetTranslatedResult((string)serializer.ReadObject(stream));    
        }

        if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError) 
        { 
            Debug.Log(unityWebRequest.error); 
        }

        StopCoroutine("TranslateWithUnityNetworking");              
    } 
} 

public static Stream GenerateStreamFromString(string incomingString) 
{ 
    MemoryStream stream = new MemoryStream(); 
    StreamWriter writer = new StreamWriter(stream); 
    writer.Write(incomingString); 
    writer.Flush(); 
    stream.Position = 0; 
    return stream; 
}

Chapter 8 – Configure the Unity Scene

  1. UnityEditorに戻って、ResultsクラスをMainCameraにAdd
  2. Resultsクラスのコンポーネントに着目
  3. Canvas>Panel>Labelオブジェクト4つ>Textの4つをResultsクラスのスロットにドラッグ(名前は揃える)
  4. TranslatorクラスをMainCameraをドラッグ
  5. MicrophoneManagerクラスをMainCameraへ
  6. Translatorクラスコンポーネントを見て、翻訳言語を選択する(From->Toにセットされた言語に翻訳される)

Chapter 9 – Test in mixed reality

やっとテストするがその前に確認: - Chapter1での設定がしっかりできているか - Results, Translator, MicrophoneManagerクラスがMainCameraにアタッチされていること - authorizationKeyはしっかり書き換えたか - MainCameraのフィールドはしっかり割り当てられているか - マイクは動いているか(マイクはデフォルトデバイスに設定されているか)

ImmersiveHeadsetをつけて再生を押してみよう

Warning

もしエラーが出たら、シーンは期待通りに動いていないかもしれない。これはmixed reality portalがヘッドセットに内臓されたマイクを使ってしまうためである。 もしエラーが出たらシンプルに一度シーンを止めて、もう一度再生してみよう

Chapter 10 – Build the UWP solution and sideload on local machine

ビルドのお時間

Delegate

概要

色んなコードを読んで出てくる、DelegateとEventは自分みたいな初心者にとっての関門でした。
一度しっかり学んで定着させたいと思いました。

Delegate

  • 関数のコンテナ
    • 関数を格納できる
    • デリゲートにメソッド(関数)を登録して、デリゲートを使うと登録したメソッドが全部一気に使えるイメージ

  • 二つの整数を使った四則演算の結果をすべて見たい
    • 例えば、1から100までの整数と3との四則演算の結果全部見たいときってありますよね(ない)

使い方

  • 登録したいメソッドを用意する
// 今回は四則演算
// 演算して結果の表示をするメソッド4つ
    void Plus(int a, int b)
    {
        print(a + "+" + b +"=" + (a + b));
    }

    void Minus(int a, int b)
    {
        print(a + "-" + b + "=" + (a - b));
    }

    void Multiplication(int a, int b)
    {
        print(a + "×" + b + "=" + (a * b));
    }

    void Division(int a, int b)
    {
        print(a + "÷" + b + "=" + (a / b));
    }
  • デリゲートの宣言
    • デリゲートは登録したい関数と、返り値の型と引数を一致させなければならない
// delegateキーワード 戻り値 デリゲートの名前 (パラメーター)
delegate void Operation(int a, int b);

// 変数を宣言
Operation op;
  • ダメな例
// 返り値の型が一致していない
delegate int Operation(int a, int b);
// 引数が一致していない
delegate void Operation(float a, float b);
  • デリゲートに格納
// Plusメソッドを代入
op = Plus;
// デリゲートには何個もメソッドを入れられる
// 追加登録するときは+=(一つ目から+=でもよい)
op += Minus;
op += Multiplication;
op += Division;

// 解除するときは-=
// op -= Division;
  • デリゲートを使う
for(int i=1; i <= 100; i++)
{
    // デリゲート変数名(引数)
    op(i, 3);
}
  • 使うときの注意 もしデリゲートに何もメソッドが登録されていない場合、使うとエラーになってしまうので、使うときはnull判定をした方がよい
if(op != null){
    op(i , 3);
}
  • 結果 1から100までの整数と3との足し算、引き算、掛け算、割り算の結果が表示されます(それだけ)

最後

今回は結果を表示するだけだったので、意味がないですが、同じメソッドを二回登録とかもできます。
Eventは次回に回します

SoftwareDesign3月号のARKit特集を読んで

概要

ARKit使って現実世界に猫を呼び出すアプリを一緒に作っていくお話が掲載されています。
すごい丁寧で分かりやすいし、作り方を一通り学びつつ、Unityの操作も学べて大変良い連続企画です。
Unity初心者なので、なんでなんだろうって思ったポイントをメモっておきます。
最初全く分からなかったのは2月号の内積で角度判定するやつ。
数式をかけるようになったらいつか書きたい。

環境

  • Unity
  • MonoDevelop
  • UnityARKitPlugin
  • Asset
    • Kitten のAssetがなくなっていた(3月号までではAssetStoreからDLできるとあった)
    • 公式githubから入手できた!!(4月号で捕捉されてた。ありがたし)

分からなかったこと

BallControl.cs

Ray ray = Camera.main.ScreenPointToRay(pos);
RaycastHit hit = new RaycastHit();
if(Physics.Raycast(ray, out hit) == false || hit.rigidbody == null){
・・・
}

という部分。

Ray

rayはある点から始まり、ある方向への無限の線。

// コンストラクタ
// originがある点, directionが方向
public Ray(Vector3 origin, Vector3 direction);

Camera.ScreenPointToRay(pos);

  • カメラのnear planeからpositionまでのワールドスペースのrayを返す。
  • posはここでは触った点
    • カメラから触った点までの3次元空間でのRayを返している

RaycastHit

  • Raycastから情報を得るために使う構造体。
    • 情報を入れ込むためにnew で箱を作る。
  • RaycastHit.rigidbody
    • ぶつかったcolliderのrigidbody

Physics.Raycast

Physics.Raycast(ray, out hit) == false
  • 引数のRayが何かcolliderと交わった場合、trueを返し、引数の hit 、つまりRaycastHit型のhitに、ぶつかった場所の情報が入る。
  • Rayが何もぶつからない場合、falseを返す。

結局

タッチした先にcollider付きのオブジェクトがない場合と、
collider付きのオブジェクトがあってもrigidbody付いてなかったらOK。
今回猫にColliderとrigidbodyを付けたから、 タッチした先に猫がいたら反応しない?のかな。
やってみる
(MacBookAirでやっていてbuildに大変手間取っています。)

参考にしたサイト

Unity - Scripting API: RaycastHit

Unity - Scripting API: Camera.ScreenPointToRay

UnityでTwitterの機能使いたい

Unityで簡単にTwitterの機能使えないかな

そんなことを思って探してみましたが、
もちろんライブラリ作ってくれてる方はいるんですね。
本当にすごい!!

qiita.com

Twityを使ってみたところ少々勉強になったことがあったんで投稿。

環境

  • Unity2017.1.2f1 (これが問題になりました)
  • VisualStudio2017 Version 15.5.5

試す

ダウンロードし、まるまるUnityのアセットに入れる。
コンパイルエラー!!!!

Assets/Twity/scripts/twitterRequest.cs(116,34): error CS1061: Type `UnityEngine.Networking.UnityWebRequest' does not contain a definition for `SendWebRequest' and no extension method `SendWebRequest' of type `UnityEngine.Networking.UnityWebRequest' could be found. Are you missing an assembly reference?

どうやら定義されていないとのこと。
定義まで掘って探してみても、確かにない。
リファレンスを調べてみました

Unity - Scripting API: Networking.UnityWebRequest.SendWebRequest

なぜないんだ?って思って、VisualStudioで定義を見てみると、

// 概要:
//     Begin communicating with the remote server.
//
// 戻り値:
//     An AsyncOperation indicating the progress/completion state of the UnityWebRequest.
//     Yield this object to wait until the UnityWebRequest is done.
public AsyncOperation Send();

怪しいものを見つけてしまいました。
調べてみると出ます

docs.unity3d.com

このURL内の 540current に変更します。
currentに変更すると今のバージョンでのリファレンスが出るのでよく使ってます。
Method group is Obsolete
google翻訳様曰く、廃れたそうです。。
悲しいですね。

Unityは新しいバージョンを出すときに、以前のバージョンのメソッド名など
変更してサポートしないことが多いそうです。

自分のUnityは2017.1でちょうど変更前だったみたいですね。

#if UNITY_2017_2
            yield return request.SendWebRequest();
#endif
#if UNITY_2017_1
            yield return request.Send();
#endif

該当箇所をif文で回避。

さらに、search/tweetsを試しました

SearchTweetsResponse Response = JsonUtility.FromJson<SearchTweetsResponse>(response);

            foreach(var status in Response.statuses)
            {
                // ツイートしたユーザー名が取れます
                Debug.Log(status.user.name);
                // ツイートされたテキストが取れます
                Debug.Log(status.text);
            }

TwitterAPIと良く読み合せればいろんなことができそう!
しばらく遊んでみます!

Unityでカメラを使う

Macのカメラを利用したい

カメラが必要なアプリケーションを作る際、
毎回デプロイして試すの面倒じゃない???
と思いやってみたものの、

Unity で Web カメラを使用する

twitter.com

↑の方が凄い丁寧にまとめられてる。。。
めっちゃ分かりやすい!!

最後の写真をローカルに保存する部分だけ、
初心者として一瞬詰まったので書きます

File.WriteAllBytes リファレンスを見てみると
File.WriteAllBytes メソッド (String, Byte[]) (System.IO)

System.IO名前空間の中に書かれています。

なので、using System.IO; を記述して、参照する。

また、

File.WriteAllBytes(Application.dataPath + "/test.png");

私は記事を見逃し、
↑のコードを書いてしまいました。

No overload for method `WriteAllBytes' takes `1' arguments

コンパイルエラー

引数一つ取るWriteAllBytesメソッドが継承されていません。 との事。

一瞬、ん?となってしまいましたが、

public static void WriteAllBytes(
    // 保存先のpath
    string path,
    // 保存したいバイトデータ
    byte[] bytes
)

リファレンス見たら一瞬でした。。恥ずかしい。 引数が足ならないだけ。。

var bytes = .... // 保存したいbyteデータ
File.WriteAllBytes(Application.dataPath + "/test.png", bytes);

これで完了です。 Application.dataPathは、Unityのプロジェクトが置かれているPath/Assets
を指しているって事くらいを学べました。

また、何枚も写真を取れるようにっていう軽い改変してみました。

// カウント用
private int count = 0;
    void Start () {
        }
    void Update () {
    //カウントアップ
               count = count + 1;
              
    //textureの貼り付けをやめる
         //GameObject.Find("Plane").GetComponent<Renderer>().material.mainTexture = texture;
    
    //ファイル名を変えていく
    File.WriteAllBytes(Application.dataPath + "/camera" + count + ".png", bytes);
        }

初めてのブログ

ブログ始めます

アウトプット用です。 当面は、Unityが初心者向けのサイトはたくさんあるけど、
ほとんどがUnityの操作ばかりで、 中級者向け(?)かつ、コードをたくさん書くものが無い気がしていて、 それを書いていきたいです。