- Home /
Putting array nr. 1 in a string ;o?
I'm trying to make a playlist. It takes values from a php file, then it makes an array of all values in Unity, and finally it's supposed to take the first value, and add it to the end of a string, example:
String = "www.google.com/" + songNames[1]; songNames : String[];
It gives me this error?
NullReferenceException: Object reference not set to an instance of an object
Radio..ctor () (at Assets/[Mit] Scripts/Radio.js:4)
Here's my javascript.
import System.IO;
var getPlaylist : String = "http://shuleii.dk/Guardian/getfiles.php";
var url : String = "http://shuleii.dk/Guardian/Playlist/" +songNames[1];
var songNames : String[];
function Start () {
var www : WWW = new WWW (getPlaylist);
yield www;
songNames = www.text.Split(","[0]);
Debug.Log("Songs: " + www.text);
}
Anyone know what I screwed up? Thank you! I'm almost finished with it then.
Answer by tanoshimi · Jun 17, 2014 at 02:57 PM
You're trying to access songNames[1]
on line 4, which is one line before you've declared the songNames
variable...
Problem is it takes time for it to get the php, so it tries to take the array 1 before. Which is what you said if I'm not wrong:>, anyways do you know any way to wait for the array to get the results, then add [1] to url? Thanks!
No, that's not what I meant... Change line 4 to just declare the variable:
var url : String;
Then assign its value at the end of the Start() function once the songNames data has been returned:
...
Debug.Log("Songs: " + www.text);
url = "http://shuleii.dk/Guardian/Playlist/" +songNames[1];
}
Answer by GrandOpener · Jun 17, 2014 at 03:35 PM
The problem, as tanoshini already described, is that you are trying to access the songNames variable prior to assigning a value to it. When you have those variable declarations at the file (class) level, they are assigned as soon as the script is first run/compiled. That's no good for you, because you don't know what the individual file urls should be until your program has already been running long enough to get the list. What you want is something more like this:
import System.IO;
var getPlaylist : String = "http://shuleii.dk/Guardian/getfiles.php";
var urlBase : String = "http://shuleii.dk/Guardian/Playlist/";
function Start () {
var www : WWW = new WWW (getPlaylist);
yield www;
Debug.Log("Songs: " + www.text);
var songNames : String[] = www.text.Split(","[0]);
for (var songUrl:String in songNames) {
Debug.Log("One song url: " + urlBase + songUrl);
// do something with the the song url here...
}
}
Also, if you have control over the PHP script, it might be easier to modify that to just return full URLs rather than filenames. Then you don't have to hardcode the extra URL in your unity code.