C# VisualStudio2019
1.したいこと
UnityのResources内にjpgファイルが追加されると、Unity内でその画像のスプライトを生成してコライダーを付加したいです。
Timersを使用して10秒ごとに監視フォルダーのファイル数をカウントし、増えたファイル数だけスプライトを生成する処理が実行されます。
2.問題点
Instantiateclone()で処理を勝手に抜けてしまいます。
コンソールにはエラーメッセージも出てこないです。
3.ソースコード
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Timers; using System.Threading.Tasks; public class Watcher : MonoBehaviour { //監視するフォルダーパス string folderPath = @"C:\hoge"; public GameObject spriteprefub; int num = 0; List<int> lengthList = new List<int>(); float correction = 0.01f; void Start() { Timer timer = new Timer(10000); timer.Elapsed += (sender, e) => { num++; Task.Run(() => { getFilePath(num); }); Debug.Log(num); }; timer.Start(); } void getFilePath(int count) { string[] filePathArray = System.IO.Directory.GetFiles(folderPath, "*"); lengthList.Add(filePathArray.Length); if (filePathArray.Length > lengthList[count - 2]) { Debug.Log("Upload"); //新しく追加されたファイル数 int newFilenumber = filePathArray.Length - lengthList[count - 2]; getNewFilePath(newFilenumber); } } void getNewFilePath(int number) { Debug.Log("ok"); //ファイルが作成されると.metaも同時に作成されるため、/2回実行 for (int i = 1; i < number / 2 + 1; i++) { //Resources.Loadのためにアップロードされた画像のパスを取得、編集(Removeの数値は気にしないで) string[] fileList = System.IO.Directory.GetFiles(folderPath, "*"); string ppath = fileList[fileList.Length - 2 * i].Remove(0, 75); string path = ppath.Remove(ppath.Length - 4, 4); Debug.Log(path); //ここから勝手に抜けてしまう GameObject sprite = instantiateclone(); instantiateSprite(path, sprite); //↓は出力されない Debug.Log("スプライトが生成されました"); } } //プレハブを生成 GameObject instantiateclone() { GameObject clone = Instantiate(spriteprefub); return clone; } void instantiateSprite(string path, GameObject clone) { //スプライトを生成 Sprite newsprite = Resources.Load(path, typeof(Sprite)) as Sprite; SpriteRenderer sprite = clone.GetComponent<SpriteRenderer>(); sprite.sprite = newsprite; //画像のサイズをコライダーに反映 BoxCollider size = clone.GetComponent<BoxCollider>(); Texture2D texture = Resources.Load(path, typeof(Texture2D)) as Texture2D; size.size = new Vector3(texture.width * correction, texture.height * correction, 100); } }
4.自分でしてみたこと
10秒ごとに監視する処理とspriteを生成する処理が同じスレッドで起動しているのがいけないのかと思い、Threading.Tasksを使用して非同期処理を試してみましたが、それでも動かず。
Instantiateclone()をStartメソッドで書くと正常に動くため、コードに問題がある訳ではないと思います。またDebugで確認したところ、instantiate直前までは作動しているみたいです。ただ繋げてみると勝手に処理を抜けるようになってしまいます。
個人的にはパソコン側の処理の問題かなと思っているのですが、そこからの見当が全くつかない状態です。
5.質問
抽象的な質問で申し訳ないのですが、Instantiateが実行されない理由としてどのような事が想定されますでしょうか?
初心者で未熟なコードではございますが、ご回答宜しくお願い致します。

回答1件
あなたの回答
tips
プレビュー