-2

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)
whoami
  • 173
  • 3
  • 15

1 Answers1

0

You are never initializing the bask in GameManager.cs.

public class GameManager : MonoBehaviour {
Basket bask;
public Text text_apple; 

// Use this for initialization
void Start () {
    bask = GameObject.Find("BaskNameInHierarchy").GetComponent<Basket>()
    text_apple.text = bask.displayApple; //i want to call the method of displayApple to get the string returned.
    }
}

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 called Basket if you're trying to reach displayApple(). Or the other way around: private shelf bask.

Fattie
  • 27,874
  • 70
  • 431
  • 719
vonis22
  • 55
  • 7
  • it work now. but i was wondering. if i uses the calling method, void Start () {long_text=_basket.DisplayApple(); Debug.Log (long_text);}, it does not have anything in console. y? if the function is void, it displays – whoami Apr 13 '16 at 05:38
  • I'm not sure what you mean. If you did exactly as you typed it should display `long_text` if `DisplayApple()` returns something. If my answer solved your problem, you can mark it as answer, so others won't come trying to solve an already solved problem. – vonis22 Apr 13 '16 at 05:46