I have class of shelf.cs and GameManager.cs. In shelf.cs, the method displayApple will return a string. Then the GameManager will access the string and display it in Text field.
shelf.cs
public class shelf: MonoBehaviour
{
//adding all the gameobjects into a list
public List<GameObject> players;
public string textApp ="";
public string displayApple()
{
for (int i = players.Count - 1; i >= 0; i--) {
if (players [i].name == "Apple") {
textApp = textApp + players [i].GetComponent<Apple> ().type + " " + players [i].GetComponent<Apple> ().colour + " " + players [i].GetComponent<Apple> ().weight;
textApp = textApp + "\n";
}
}
long_apple= textApp;
return long_apple;
}
}
then in GameManager.cs
public class GameManager : MonoBehaviour {
Basket bask;
public Text text_apple;
// Use this for initialization
void Start () {
text_apple.text = bask.displayApple; //i want to call the method of displayApple to get the string returned.
}
}
The text field wont display the string and there are errors.
NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () (at Assets/scripts/GameManager.cs:12)
You are never initializing the bask in
GameManager.cs
.You can also make the bask public
public Basket bask;
. Then drag a GameObject into the inspector on the GameObject that the script is attached to.Also the
Shelf
script should be calledBasket
if you're trying to reachdisplayApple()
. Or the other way around:private shelf bask
.