LoginSignup
5
7

More than 5 years have passed since last update.

[Unity] ドラッグ&ドロップ一切使わずスクリプトのみで画像・動画・テキスト・Prefab取り込み

Last updated at Posted at 2017-06-21

D&Dに頼らずアセットをシーンに…

この状態からスクリプトだけで色々取り込む
1_first.png

前提

  • HoloLens上での動作を目指しています
  • D&Dなし(くりかえし)
  • スクリプトのみ(くりかえし)

環境

Unity 5.6.1f1 Personal
HoloLens OS build 10.0.14393.1198
HoloToolKit Merge #716

アセット

  • 画像(png,jpg) ※360度ビュー可
  • 動画(ogv) ※360度ビュー可
  • テキスト(txt, json)
  • 3Dモデル(fbx)

360度視野の画像・動画は専用の球体のPrefabをPlaneの代わりに作れば可能ですがここでは割愛

Tree

Project
Assets
├── StreamingAssets
│   └───Resources
│        ├──images
│        │   └── exIm.png
│        ├──movies
│        │   └── exMv.ogv
│        ├──texts
│        │   └── exTx.txt
│        └──models
│            ├── exMd.fbx
│            └───Prefabs
│                └──model.prefab
└─── Prefabs
     └──3DTextPrefab.prefab

PrefabsファイルはResources内で一つにまとめても良い

streamingAssetsについてはHoloLens上でスクリプトを用いて外部ファイルの読み込みをしたいを参照

using
using UnityEngine;

//テキスト読み込み用
using System.IO;
using System.Text;

画像

Planeを生成して画像を2Dテクスチャとして貼り付ける

画像
GameObject image = GameObject.CreatePrimitive(PrimitiveType.Plane);
string path = "images/exIm" //Resources.Loadのために拡張子つけない
Renderer rend = image.GetComponent<Renderer>();
Texture2D tex2d = new Texture2D(1, 1); //コンストラクタの値はなんでも良い
//Photo読み込み
tex2d = Resources.Load(path) as Texture2D;
//PlaneのTextureに画像を指定
rend.material.mainTexture = tex2d;

動画

Unity 5.6からはVideoPlayerというのが使えるらしい…

動画
GameObject movie = GameObject.CreatePrimitive(PrimitiveType.Plane);
string path = "images/exMv" //Resources.Loadのために拡張子つけない
Renderer rend = movie.GetComponent<Renderer>();
//Movie読み込み
MovieTexture movieTexture = Resources.Load(path) as MovieTexture;
//Audio取り付け・読み込み
AudioSource audioSource = movie.AddComponent<AudioSource>();
audioSource.clip = movie.audioClip;

//PlaneのTextureに動画を指定
rend.material.mainTexture = movieTexture;
//再生
movieTexture.Play();
audioSource.Play();


テキスト

textPrefabはHoloToolKit-UnityUI/Prefabs/UITextPrefab.prefabを使用

テキスト
//ーー関数外ーー
public GameObject textPrefab;//ここD&D使ってました(その気になればこれも読み込みできるはず)
//ーーーーーーー

GameObject textGO = Instantiate(textPrefab);
TextMesh text3d = textGO.GetComponent<>();
string path = Application.streamingAssetsPath 
    + "/Resources/texts/exTx.txt";
FileInfo file = new FileInfo(path) // フルパス・拡張子必要

using (StreamReader sr = new StreamReader(file.OpenRead(), Encoding.UTF8)
{

    string text = sr.ReadToEnd();
    text3d.text = text;
   //Close() メソッドはWindows Store系アプリの場合使えないのでDispose()で代用
    sr.Dispose(); //↑結構大事
}

3Dモデル

モデル
GameObject prefab = Resources.Load("models/Prefabs/model");
GameObject model = Instantiate(prefab);

以上

よりダイナミカルなシーンを組むことが可能に

HoloLens開発記事一覧

こちらから

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7