Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Return string to be accessed from other class

Discussion in 'Scripting' started by happy_life, Apr 12, 2016.

  1. happy_life

    happy_life

    Joined:
    Apr 11, 2016
    Posts:
    12
    I have the function of displaytext in blue.cs. It should return a string of textApp. Then ocean.cs will access the string textApp and use it for display.
    How do I modify this code? and how can i access it from ocean.cs

    blue.cs
    Code (CSharp):
    1. void displaytext()
    2.     {
    3.         for(int i = players.Count - 1; i >= 0; i--)
    4.         {
    5.             if(players[i].name == "miao")
    6.             {
    7.                 textApp= textApp + players[i].GetComponent<miao>().type+" " + players[i].GetComponent<miao>().colour+" " + players[i].GetComponent<miao>().weight;
    8.                 textApp= textApp+ "\n";
    9.             }
    10.         }
    11. }
     
  2. SlyRipper

    SlyRipper

    Joined:
    Jun 19, 2012
    Posts:
    251
    there are several ways to achieve this, one would be to make the method static, that way you can access it from every class, but it might change it's behaviour, and is not the way you want it to work.
    Another way would be to simply add a public property of your blue script inside the ocean script file, attach the blue script to that property and you can simply access the variable if it's public (if nothing stands in front of your void, it's default is private, so you have to add the "public" word in front of it)
     
  3. happy_life

    happy_life

    Joined:
    Apr 11, 2016
    Posts:
    12
    Is the second way something like this?

    Code (CSharp):
    1. myObject.GetComponent<MyScript>().MyFunction();
     
  4. SlyRipper

    SlyRipper

    Joined:
    Jun 19, 2012
    Posts:
    251