Find a string in an array from another script
I have two objects, one contains a script that generates an array of player stats. I would like to use the second object to generate gui labels of the player data. The aim is to create a way for the player to browse through multiple player stats.
here is the code for the array generation. using UnityEngine;
public class PlayerGenerator : MonoBehaviour {
public class player
{
public string name;
}
public TextAsset namelist; //Set namelist as asset
public player[] playerpool = new player[51]; //create an array
void Start() {
var names = namelist.text.Split("\n"[0]);
float nameValue;
for (int i = 1; i < 50; i++)
{
nameValue = UnityEngine.Random.Range(0, 49);
playerpool[i].name = names[(int)portraitValue];
}
}
}
and here is the code for the script to show the labels.
public class GUImanager : MonoBehaviour {
public PlayerGenerator playerArray;
private void OnGUI()
{
string name = playerArray.playerpool[0].name;
GUI.Label(new Rect(460, 70, 150, 25),name);
}
Thanks any help greatly appreciated.
sorry playerpool[i].name = names[(int)portraitValue]; should be playerpool[i].name = names[(int)nameValue];
The error I am getting is NullReferenceException: Object reference not set to an instance of an object GUImanager.OnGUI () (at Assets/Scenes/GUImanager.cs:10)
Try changing Start() to Awake(). Are you still getting errors?
Answer by pekalicious · Nov 12, 2015 at 08:49 AM
This line will not create players, it will only create an array that will eventually contain players: public player[] playerpool = new player[51]; //create an array
So when you do this: player[0].name
you are saying "Get the player at index 0 from the array, and set its name". But since you haven't actually set any player at that index, it crashes.
To set the player, you simply create one and put it in the array:
for (int i = 1; i < 50; i++)
{
nameValue = UnityEngine.Random.Range(0, 49);
playerpool[i] = new player(); // Create the player and add it to the array
playerpool[i].name = names[(int)portraitValue];
}
Also, I'm not sure if OnGUI is called after Start, so you might want to try changing Start to Awake, just to be sure that you have created the array before anybody tries to access it.
this is what my brain wouldnt let me say this morning before work :D
Answer by bubzy · Nov 12, 2015 at 07:49 AM
using UnityEngine;
using System.Collections;
public class PlayerGenerator : MonoBehaviour {
[System.Serializable] //just to show in editor window
public class player
{
public string name;
public player(string _name)
{
name = _name;
}
}
public player[] playerpool = new player[20] ;
void Start() {
for (int i = 0; i < 10; i++) {
playerpool[i] = new player("Player " + i);
}
}
}
this works, sorry im out of time to try and work out the problem with yours this morning (work calls) hope this helps