Unity 5.6 VideoPlayer: Larger videos does not leave (videoPlayer.isPlaying) loop? - c#

I started to experiment with the new Unity beta 5.6 Video Player. I have made a media player to loop images and videos from a folder (url) on a RawImage.
When I add larger video files (trailers) to the folder, at some point pretty soon the Player gets stuck after the video has ended and does not leave the while (videoPlayer.isPlaying) loop. At same time the rendering stops completely from the profiler tool. This does not happen with smaller & shorter video clips.
Also there is a small bug with audio. The audio wont play on first loop with first video file. After that it plays fine.
Have I made some mistake or could this be a bug in the beta? I have only tested with .mp4 videos.
Edit: Seems like a workaround fix for now is to add videoPlayer.isLooping = true; after videoPlayer.Play(); command. Code updated.
Code so far ->
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using UnityEngine.Video;
public class Play : MonoBehaviour
{
// Use this for initialization
bool develop = true;
bool web = false;
//UI & Audio
private VideoPlayer videoPlayer;
private VideoSource videoSource;
private AudioSource audioSource;
//Local
private string path = "file://";
private string folder = "C:/medias/";
private WaitForSeconds waitTime;
int arrLength;
int i = 0;
//Web (http)
private string webpath = "http://";
string uri = "www.rtcmagazine.com/files/images/5353/";
string source;
string str;
WWW www;
//Extensions to get
string[] extensions = new[] { ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".mp4", ".MP4", ".webm", ".WEBM", ".avi", ".AVI" };
FileInfo[] info;
DirectoryInfo dir;
void Start()
{
//Add VideoPlayer to the GameObject
videoPlayer = gameObject.AddComponent<VideoPlayer>();
//Add AudioSource
audioSource = gameObject.AddComponent<AudioSource>();
//Disable Play on Awake for both Video and Audio
videoPlayer.playOnAwake = true;
audioSource.playOnAwake = true;
if (web) {
string[] fetchFilesCount = GetFiles (webpath+uri);
int getLenght = fetchFilesCount.Length;
info = new FileInfo[getLenght];
int counter = 0;
string[] filesFromWeb = GetFiles (webpath+uri);
foreach (String file in filesFromWeb)
{
info [counter] = new FileInfo(webpath+uri+file);
counter++;
if (counter == filesFromWeb.Length) {
counter = 0;
}
}
} else {
info = new FileInfo[]{};
dir = new DirectoryInfo(#folder);
info = dir.GetFiles().Where(f => extensions.Contains(f.Extension.ToLower())).ToArray();
}
arrLength = info.Length;
Application.runInBackground = true;
StartCoroutine(looper());
}
IEnumerator looper()
{
//Run forever
while (true)
{
if (i == arrLength - 1)
{
if (web) {
int counter = 0;
string[] filesFromWeb = GetFiles (webpath+uri);
foreach (String file in filesFromWeb)
{
info [counter] = new FileInfo(webpath+uri+file);
counter++;
if (counter == filesFromWeb.Length) {
counter = 0;
}
}
} else {
info = dir.GetFiles ().Where (f => extensions.Contains (f.Extension.ToLower ())).ToArray ();
arrLength = info.Length;
}
i = 0;
}
else
{
i++;
}
//Debug.Log(info[i]);
yield return StartCoroutine(medialogic());
int dotIndex = info[i].ToString().LastIndexOf('.');
//string lhs = index < 0 ? source : source.Substring(0,index),
string searchDot = dotIndex < 0 ? "" : source.Substring(dotIndex+1);
int dotPos = Array.IndexOf(extensions, "." + searchDot);
if (dotPos > 5) {
waitTime = new WaitForSeconds (0);
} else {
waitTime = new WaitForSeconds (7);
}
//Wait for 7 seconds
yield return waitTime;
}
}
IEnumerator medialogic()
{
source = info[i].ToString();
if (web) {
if (develop) {
www = new WWW (source);
} else {
www = new WWW (webpath+uri+source);
}
} else {
if (develop) {
str = path + source;
} else {
str = path + folder + source;
}
www = new WWW (str);
}
int index = source.LastIndexOf('.');
//string lhs = index < 0 ? source : source.Substring(0,index),
string rhs = index < 0 ? "" : source.Substring(index+1);
int pos = Array.IndexOf(extensions, "." + rhs);
if (pos > -1 && pos < 6)
{
//Wait for download to finish
yield return www;
GetComponent<RawImage>().texture = www.texture;
}
else if (pos > 5)
{
//videos here
videoPlayer.source = VideoSource.Url;
videoPlayer.url = str;
//Set Audio Output to AudioSource
videoPlayer.audioOutputMode = VideoAudioOutputMode.AudioSource;
//Assign the Audio from Video to AudioSource to be played
videoPlayer.EnableAudioTrack(0, true);
videoPlayer.SetTargetAudioSource(0, audioSource);
//Set video To Play then prepare Audio to prevent Buffering
videoPlayer.Prepare();
while (!videoPlayer.isPrepared)
{
yield return null;
}
//Assign the Texture from Video to RawImage to be displayed
GetComponent<RawImage>().texture = videoPlayer.texture;
//Play Video
videoPlayer.Play();
//Play Sound
audioSource.Play();
//Set loop to true, hack for a freeze bug
videoPlayer.isLooping = true;
//Alternative way to check if video has ended
videoPlayer.loopPointReached += EndReached;
Debug.Log ("Play started");
while (videoPlayer.isPlaying)
{
Debug.Log ("---Playing---");
yield return null;
}
Debug.Log("Done Playing Video");
}
}
void EndReached(UnityEngine.Video.VideoPlayer videoPlayer) {
Debug.Log("End reached!");
//Play Video
videoPlayer.Stop();
//Play Sound
audioSource.Stop();
}
public static string[] GetFiles(string url)
{
string[] extensions2 = new[] { ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG", ".mp4", ".MP4", ".webm", ".WEBM", ".avi", ".AVI" };
List<string> files = new List<string>(500);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string html = reader.ReadToEnd();
Regex regex = new Regex("(?<name>.*)");
MatchCollection matches = regex.Matches(html);
if (matches.Count > 0)
{
foreach (Match match in matches)
{
if (match.Success)
{
string[] matchData = match.Groups[0].ToString().Split('\"');
foreach (string x in extensions2)
{
if (match.ToString().Contains(x))
{
files.Add(matchData[1]);
}
}
//files.Add(matchData[1]);
}
}
}
}
}
return files.ToArray();
}
public static string[] getFtpFolderItems(string ftpURL)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL);
request.Method = WebRequestMethods.Ftp.ListDirectory;
//You could add Credentials, if needed
//request.Credentials = new NetworkCredential("anonymous", "password");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
return reader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
}
Thanks for your time :)

Related

C#+VideoLan.LibVLC Sample Audio Stream and save it to disk

I am using VideoLan.VLC to get 20 seconds of an audio stream every 30 seconds.
I have a loop, something like
private LibVLC libvlc = new LibVLC();
private MediaPlayer mediaPlayer = null;
private Media Media = null;
private string AudioSampleFileName { get {
return "audio_" + DateTime.Now.ToString("yyyyMMdd_HHmmss")+
".ts";
} }
public void Start(){
mediaPlayer = new MediaPlayer(libvlc);
while(...){
Get_20_seconds_audio_sample();
Wait_30_Seconds();
}
}
public void Get_sample(Uri playPathUri, string FileName)
{
var currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var destination = Path.Combine(currentDirectory, FileName);
var mediaOptions = new string[]
{
":sout=#file{dst=" + destination + ",channels=1,samplerate=16000}",
":sout-keep"
};
if (Media == null)
{
Media = new Media(libvlc, playPathUri, mediaOptions);
mediaPlayer.Media = Media;
}
else {
Media.AddOption(":sout=#file{dst=" + destination + ",channels=1,samplerate=16000}");
}
mediaPlayer.Play();
}
public void Get_20_seconds_audio_sample(){
Get_sample(RadioURI,AudioSampleFileName);
Wait_20_seconds();
Stop();
}
public void Stop()
{
mediaPlayer.Stop();
}
The Problem is that radio streming ususally starts with a commercial that lasts about 25 seconds. Every sample plays the commercial. It seems that Stop() closes the stream until Play() is called again and it restart the stream. I tired to pause the audio but, well...it makes no much sense to pause and play.
I can accept to get the commercial only in the first sample but then I want the regular radio audio. Is there a way not to close the stream every time? I am not tied to VideoLan dll so I can start from scratch if you have a better way to do it.
Use Audio callbacks and save the audio stream yourself. Full sample:
class Program
{
// This sample shows you how you can use SetAudioFormatCallback and SetAudioCallbacks. It does two things:
// 1) Play the sound from the specified video using NAudio
// 2) Extract the sound into a file using NAudio
static void Main(string[] args)
{
Core.Initialize();
using var libVLC = new LibVLC(enableDebugLogs: true);
using var media = new Media(libVLC,
new Uri("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"),
":no-video");
using var mediaPlayer = new MediaPlayer(media);
using var outputDevice = new WaveOutEvent();
var waveFormat = new WaveFormat(8000, 16, 1);
var writer = new WaveFileWriter("sound.wav", waveFormat);
var waveProvider = new BufferedWaveProvider(waveFormat);
outputDevice.Init(waveProvider);
mediaPlayer.SetAudioFormatCallback(AudioSetup, AudioCleanup);
mediaPlayer.SetAudioCallbacks(PlayAudio, PauseAudio, ResumeAudio, FlushAudio, DrainAudio);
mediaPlayer.Play();
mediaPlayer.Time = 20_000; // Seek the video 20 seconds
outputDevice.Play();
Console.WriteLine("Press 'q' to quit. Press any other key to pause/play.");
while (true)
{
if (Console.ReadKey().KeyChar == 'q')
break;
if (mediaPlayer.IsPlaying)
mediaPlayer.Pause();
else
mediaPlayer.Play();
}
void PlayAudio(IntPtr data, IntPtr samples, uint count, long pts)
{
int bytes = (int)count * 2; // (16 bit, 1 channel)
var buffer = new byte[bytes];
Marshal.Copy(samples, buffer, 0, bytes);
waveProvider.AddSamples(buffer, 0, bytes);
writer.Write(buffer, 0, bytes);
}
int AudioSetup(ref IntPtr opaque, ref IntPtr format, ref uint rate, ref uint channels)
{
channels = (uint)waveFormat.Channels;
rate = (uint)waveFormat.SampleRate;
return 0;
}
void DrainAudio(IntPtr data)
{
writer.Flush();
}
void FlushAudio(IntPtr data, long pts)
{
writer.Flush();
waveProvider.ClearBuffer();
}
void ResumeAudio(IntPtr data, long pts)
{
outputDevice.Play();
}
void PauseAudio(IntPtr data, long pts)
{
outputDevice.Pause();
}
void AudioCleanup(IntPtr opaque) { }
}
}

SpeechSynthesizer inside for loop not iterating in unity

I am modifying the code from https://github.com/Azure-Samples/cognitive-services-speech-sdk/blob/master/quickstart/csharp/unity/text-to-speech/Assets/Scripts/HelloWorld.cs to make it count from 1 to 10. While the iteration is displayed fine in the console but the system only says "ten".
I am trying to make it say "one", "two", "three" .... "ten" using for loop.
What am I missing?
using UnityEngine;
using UnityEngine.UI;
using Microsoft.CognitiveServices.Speech;
using System.Threading.Tasks;
public class HelloWorld : MonoBehaviour
{
// Hook up the three properties below with a Text, InputField and Button object in your UI.
public Text outputText;
public InputField inputField;
public Button speakButton;
public AudioSource audioSource;
private object threadLocker = new object();
private bool waitingForSpeak;
private string message;
private SpeechConfig speechConfig;
private SpeechSynthesizer synthesizer;
public void ButtonClick()
{
// Starts speech synthesis, and returns after a single utterance is synthesized.
for (int j = 1; j <= 10; j++)
{
Debug.Log("Iteration: " + j);
using (var result = synthesizer.SpeakTextAsync(j.ToString()).Result)
{
// Checks result.
if (result.Reason == ResultReason.SynthesizingAudioCompleted)
{
var sampleCount = result.AudioData.Length / 2;
var audioData = new float[sampleCount];
for (var i = 0; i < sampleCount; ++i)
{
audioData[i] = (short)(result.AudioData[i * 2 + 1] << 8 | result.AudioData[i * 2]) / 32768.0F;
}
// The output audio format is 16K 16bit mono
var audioClip = AudioClip.Create("SynthesizedAudio", sampleCount, 1, 16000, false);
audioClip.SetData(audioData, 0);
audioSource.clip = audioClip;
audioSource.Play();
newMessage = "Speech synthesis succeeded!";
}
else if (result.Reason == ResultReason.Canceled)
{
var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
newMessage = $"CANCELED:\nReason=[{cancellation.Reason}]\nErrorDetails=[{cancellation.ErrorDetails}]\nDid you update the subscription info?";
}
}
}
}
void Start()
{
if (outputText == null)
{
UnityEngine.Debug.LogError("outputText property is null! Assign a UI Text element to it.");
}
else if (inputField == null)
{
message = "inputField property is null! Assign a UI InputField element to it.";
UnityEngine.Debug.LogError(message);
}
else if (speakButton == null)
{
message = "speakButton property is null! Assign a UI Button to it.";
UnityEngine.Debug.LogError(message);
}
else
{
inputField.text = "Enter text you wish spoken here.";
message = "Click button to synthesize speech";
speakButton.onClick.AddListener(ButtonClick);
speechConfig = SpeechConfig.FromSubscription("YourSubscriptionKey", "northeurope");
// The default format is Riff16Khz16BitMonoPcm.
// We are playing the audio in memory as audio clip, which doesn't require riff header.
// So we need to set the format to Raw16Khz16BitMonoPcm.
speechConfig.SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat.Raw16Khz16BitMonoPcm);
// Creates a speech synthesizer.
// Make sure to dispose the synthesizer after use!
synthesizer = new SpeechSynthesizer(speechConfig, null);
}
}
void Update()
{
lock (threadLocker)
{
if (speakButton != null)
{
speakButton.interactable = !waitingForSpeak;
}
if (outputText != null)
{
outputText.text = message;
}
}
}
void OnDestroy()
{
synthesizer.Dispose();
}
}
I ended up doing the following and it's working as I wanted. Basically made the button click function to async and awaited for the synthesizer.
public async void ButtonClick()
{
Debug.Log("Button Pressed!");
for (int j = 1; j <= 10; j++)
{
string newMessage = string.Empty;
var config = SpeechConfig.FromSubscription("KEY", "northeurope");
using var synthesizer = new SpeechSynthesizer(config);
await synthesizer.SpeakTextAsync(j.ToString());
}
}

Why when destroying the original object the temp new object is null?

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PrefabReplace : EditorWindow
{
[SerializeField] private GameObject prefab;
GameObject newobj;
[MenuItem("Tools/Prefab Replace")]
static void CreateReplaceWithPrefab()
{
EditorWindow.GetWindow<PrefabReplace>();
}
private void OnGUI()
{
prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab, typeof(GameObject), false);
if (GUILayout.Button("Replace"))
{
var selection = Selection.gameObjects.ToList();
if (prefab != null && selection.Count > 0)
{
for (var i = selection.Count - 1; i >= 0; --i)
{
var selected = selection[i];
var prefabType = PrefabUtility.GetPrefabType(prefab);
GameObject newObject;
if (prefabType == PrefabType.Prefab)
{
newObject = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
}
else
{
newObject = Instantiate(prefab);
newObject.name = prefab.name;
}
if (newObject == null)
{
Debug.LogError("Error instantiating prefab");
break;
}
Undo.RegisterCreatedObjectUndo(newObject, "Replace With Prefabs");
newObject.transform.parent = selected.transform.parent;
newObject.transform.localPosition = selected.transform.localPosition;
newObject.transform.localRotation = selected.transform.localRotation;
newObject.transform.localScale = selected.transform.localScale;
newObject.transform.SetSiblingIndex(selected.transform.GetSiblingIndex());
Undo.DestroyObjectImmediate(selected);
}
}
}
if (GUILayout.Button("Write settings"))
{
var selection = Selection.gameObjects.ToList();
if (selection.Count > 0)
{
for (int i = selection.Count - 1; i >= 0; --i)
{
var selected = selection[i].transform;
string toWrite = $"{selected.parent}:{selected.localPosition}:{selected.localRotation}:{selected.localScale}";
WriteDataToFile(toWrite);
}
}
}
if (GUILayout.Button("Read settings"))
{
var obj = GetObjectFromFile("Assets/Resources/test.txt");
Instantiate(obj);
DestroyImmediate(newobj);
}
GUI.enabled = false;
EditorGUILayout.LabelField("Selection count: " + Selection.objects.Length);
}
private void OnInspectorUpdate()
{
Repaint();
}
private void WriteDataToFile(string line)
{
string path = "Assets/Resources/test.txt";
StreamWriter writer = new StreamWriter(path, true);
writer.WriteLine(line);
writer.Close();
}
private GameObject GetObjectFromFile(string path)
{
newobj = new GameObject();
string[] text = new string[3];
if (File.Exists(path))
{
text = File.ReadAllLines(path);
foreach (string s in text)
{
text = s.Split(':');
break;
}
var parent = text[0].Substring(0, text[0].IndexOf(" ("));
var localPosition = StringToVector3(text[1]);
var localRotation = StringToQuaternion(text[2]);
var localScale = StringToVector3(text[3]);
if (parent != null)
{
GameObject toparent = GameObject.Find(parent);
newobj.transform.parent = toparent.transform;
}
newobj.transform.localPosition = localPosition;
newobj.transform.localRotation = localRotation;
newobj.transform.localScale = localScale;
}
return newobj;
}
public static Vector3 StringToVector3(string sVector)
{
// Remove the parentheses
if (sVector.StartsWith("(") && sVector.EndsWith(")"))
{
sVector = sVector.Substring(1, sVector.Length - 2);
}
// split the items
string[] sArray = sVector.Split(',');
// store as a Vector3
Vector3 result = new Vector3(
float.Parse(sArray[0]),
float.Parse(sArray[1]),
float.Parse(sArray[2]));
return result;
}
public static Quaternion StringToQuaternion(string sQuaternion)
{
// Remove the parentheses
if (sQuaternion.StartsWith("(") && sQuaternion.EndsWith(")"))
{
sQuaternion = sQuaternion.Substring(1, sQuaternion.Length - 2);
}
// split the items
string[] sArray = sQuaternion.Split(',');
// store as a Vector3
Quaternion result = new Quaternion(
float.Parse(sArray[0]),
float.Parse(sArray[1]),
float.Parse(sArray[2]),
float.Parse(sArray[3]));
return result;
}
}
When I put a break point on the line:
DestroyImmediate(newobj);
I see that the variable obj is fine and not null.
But then when I click continue once I see that the variable obj is null.
I'm destroying the newobj then why it can't remember the values that was in obj ? I don't want to make new instance for obj since it will add a new GameObject to the hierarchy. I want only to assign the values to a new gameobject.
If you want to assign a new object with the same data use the structure of:
var newobj = new Type(oldObj);
This will copy the contents across and leave you with 2 seperate objects.
E.g var obj = new ObjectClass(GetObjectFromFile("Assets/Resources/test.txt"));

ForEach Loop, Execute Command for Each Randomly Named Image

I'm using Movie Maker Timeline Control in C# to try and randomize the order of pictures in Windows Movie Maker. I have the form set up, but I seem to encounter a problem with the importing of photos. My code needs to be able to import multiple randomly named images (ex: IMG_xxxx.JPG). I'm able to individually import a specifically named image, but when I try to use a foreach loop, it fails.
My code:
private void btnOpen_Click(object sender, EventArgs e)
{
openFolder.Description = "Open a folder containing pictures for the slideshow!";
if (openFolder.ShowDialog() == DialogResult.OK)
{
// this code right here
string folderPath = openFolder.SelectedPath;
string[] fileArray = Directory.GetFiles(folderPath, "*.JPG");
foreach (string file in fileArray)
{
folderPath = folderPath + "\\" + file;
float duration = 4;
float startpos = 0;
timelineControl.AddImageClip(timelineControl.GetImageTrackIndex(), folderPath, startpos, (startpos + duration));
startpos = startpos + 4;
}
/* string image = "C:\\Users\\OSR\\Desktop\\jpgs\\img.JPG";
float duration = 4;
timelineControl.AddImageClip(timelineControl.GetImageTrackIndex(), image, 0, duration);
*/
}
else
{
MessageBox.Show("Next time, select a folder and click open!", "Selection Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Full code: https://pastebin.com/MrB928Ri
Program: http://imgur.com/a/bikxU
You are destroying the folderPath in the loop:
var folderPath = openFolder.SelectedPath;
var fileArray = Directory.GetFiles(folderPath, "*.JPG");
float duration = 4;
float startpos = 0;
foreach (var file in fileArray) {
var filePath = $#"{folderPath}\{file}";
timelineControl.AddImageClip(timelineControl.GetImageTrackIndex(), filePath, startpos, (startpos + duration));
startpos += 4;
}

Nav buttons need to be pressed twice to advance through Array

I created a pair of nav buttons (next and previous) to navigate through an array of images but something stange is happening at the beginning and end of the array. I have to hit the next or previous button twice to move forward or back. Once I do that at the beginning or end of the array everything works normally. Can someone see what's going wrong?
public Texture2D tex;
public string[] galleryImages;
public Button nextBtn;
public Button prevBtn;
int randomIndex;
int currentIndex = 0;
public Color inactiveColor = new Color(0.2F, 0.3F, 0.4F, 0.5F);
string[] arctopithecusImages;
string[] arctopithecusPNGImages;
string[] gulonImages;
string[] scythianWolfImages;
string[] simivulpaImages;
string[] succorathImages;
string[] tatusImages;
// System.Random rand = new System.Random();
// Create a master Array of all image files located in all Image locations
void Start()
{
// Build Gallery Arrays
arctopithecusImages = Directory.GetFiles(#"/Users/kenmarold/Screenshots/ARCTOPITHECUS/", "*.jpg");
arctopithecusPNGImages = Directory.GetFiles(#"/Users/kenmarold/Screenshots/ARCTOPITHECUS/", "*.png");
gulonImages = Directory.GetFiles(#"/Users/kenmarold/Screenshots/GULON/", "*.jpg");
scythianWolfImages = Directory.GetFiles(#"/Users/kenmarold/Screenshots/SCYTHIAN-WOLF/", "*.png");
simivulpaImages = Directory.GetFiles(#"/Users/kenmarold/Screenshots/SIMIVULPA/", "*.png");
succorathImages = Directory.GetFiles(#"/Users/kenmarold/Screenshots/SUCCORATH/", "*.png");
tatusImages = Directory.GetFiles(#"/Users/kenmarold/Screenshots/TATUS/", "*.png");
// Concatenate all Folder Array into single Array
galleryImages =
arctopithecusImages.Concat(arctopithecusPNGImages)
.Concat(gulonImages)
.Concat(scythianWolfImages)
.Concat(simivulpaImages)
.Concat(succorathImages)
.Concat(tatusImages)
.ToArray();
Debug.Log(galleryImages.Length);
}
IEnumerator loader(int indexNum)
{
WWW www = new WWW("file://" + galleryImages[indexNum]); // get the first file from disk
yield return www; // Wait unill its loaded
tex = new Texture2D(512,512); // create a new Texture2D
www.LoadImageIntoTexture(tex); // put the image file into the new Texture2D
Rect rct = new Rect(0, 0, tex.width, tex.height);
Vector2 pvt = new Vector2(0.5f, 0.5f);
GameObject screenShotImg = GameObject.FindGameObjectWithTag("GalleryImgHolder");
Image img = screenShotImg.GetComponent<Image>();
img.sprite = Sprite.Create(tex, rct, pvt);
}
public void LoadImg()
{
if(tex == null)
{
StartCoroutine("loader", currentIndex);
Debug.Log(currentIndex);
} else {
currentIndex = Random.Range(0,galleryImages.Length);
StartCoroutine("loader", currentIndex);
Debug.Log(currentIndex);
}
}
public void nextImage()
{
Debug.Log(currentIndex);
// Increment through gallery
if(currentIndex != galleryImages.Length - 1)
{
StartCoroutine("loader", currentIndex++);
prevBtn.enabled = true;
prevBtn.interactable = true;
nextBtn.enabled = true;
nextBtn.interactable = true;
// nextBtn.image.color = new Color(255f,255f,255f,1f);
} else if (currentIndex == galleryImages.Length - 1){
nextBtn.enabled = false;
nextBtn.interactable = false;
// nextBtn.image.color = new Color(255f,255f,255f,.5f);
}
}
public void prevImage()
{
Debug.Log(currentIndex);
// Decrement through gallery
if(currentIndex != 0)
{
StartCoroutine("loader", currentIndex--);
nextBtn.enabled = true;
nextBtn.interactable = true;
prevBtn.enabled = true;
prevBtn.interactable = true;
// prevBtn.image.color = new Color(255f,255f,255f,1f);
} else if (currentIndex == 0){
prevBtn.enabled = false;
prevBtn.interactable = false;
// prevBtn.image.color = new Color(255f,255f,255f,.5f);
}
}
}
Your yield return is the problem, that's not how its supposed to be used, if you want to wait for asynchronous methods to finish, learn how to use async/await.

Categories