Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9743

【Unity】ニコニコ動画みたいなコメント弾幕機能を作る

$
0
0

入力したコメントが右から左へ流れていくアレを実装します。

【環境】

・Mac OSX El Capitan
・Unity versiton:2018.3.0

【結果】

https://youtu.be/yNzuOzIHNgU

【作り方】

最終的な配置イメージ
スクリーンショット 2020-09-07 21.25.00.png

まずはInputFieldを作成します。
InputFieldコンポーネントのLineTypeをMultiLineNewLineにします。
※SingleLineのままだと日本語入力ができないので注意!

 こちらを参考にさせていただきました。
 http://chnr.hatenablog.com/entry/2015/03/06/011559

次にシーンにTextオブジェクトを作成します。
作成したTextオブジェクトの名前をTextPrefabに変更して下記スクリプトをアタッチします。

TextPrefab.cs
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassTextPrefab:MonoBehaviour{privateVector2startPos;privateRectTransformrectTransform;publicfloatspeed;// Start is called before the first frame updatevoidStart(){rectTransform=this.gameObject.GetComponent<RectTransform>();floatheight=Screen.height;floatMaxHeight=height/2;floatMinHeight=-MaxHeight;floatwidth=Screen.width;floattextHeight=rectTransform.sizeDelta.y;floattextWidth=rectTransform.sizeDelta.x;//最初の位置を画面右端にするstartPos=newVector2(width/2+textWidth/2,Random.Range(MinHeight+textHeight/2,MaxHeight+textHeight/2));rectTransform.localPosition=startPos;}// Update is called once per framevoidUpdate(){//speedに応じて画面右から左へ流れていくtransform.Translate(-speed*Time.deltaTime,0,0);//画面外へ出た場合は自身を削除するif(transform.localPosition.x<-Screen.width/2-rectTransform.sizeDelta.x/2){Destroy(this.gameObject);}}}

TextコンポーネントのRaycastTargetのチェックを外します。
※チェックがついたままだと、テキストがボタンの上を通過する際にボタンが押せなくなるので注意!

シーン上のTextPrefabをプレハブ化し、シーンに残っている方は削除します。

そして、Buttonオブジェクトを作成し、下記のGenerateText.csをアタッチします。

GenerateText.cs
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEngine.UI;publicclassGenerateText:MonoBehaviour{publicGameObjecttextPrefab;privateTexttext;publicInputFieldinputField;publicfloatspeed=200;// Start is called before the first frame updatevoidStart(){text=textPrefab.GetComponent<Text>();inputField=inputField.GetComponent<InputField>();}publicvoidGenerateTextPrefab()//テキストプレハブのテキストにインプットフィールドのテキストを代入して生成し、スピードを設定する。{text.text=inputField.text;GameObjectnewTextObj=(GameObject)Instantiate(textPrefab,transform.parent);newTextObj.GetComponent<TextPrefab>().speed=speed;}}

InspectorでTextPrefab,InputFieldを代入。
Speedは任意の値を入れてください。
(だいたい200以上がいい感じです)

ButtonコンポーネントのOnClick()の+ボタンをクリックして新しい項を作成し、自身のButtonオブジェクトを入れます。
プルダウンからGenerateText/GenerateTextPrefabを選択します。
これでボタンを押すとTextPrefabが生成される機能が実装されました。

スクリーンショット 2020-09-07 9.18.24.png

本家のディテールに合わせるなら、文字数に合わせて速度が変えるとよさそう。
あとは文字数に合わせてTextPrefabのサイズを変更するとベター。
実装したら追記します。


Viewing all articles
Browse latest Browse all 9743

Trending Articles