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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Read the text file real-time after build

Discussion in 'Scripting' started by Woogler, Jun 4, 2015.

  1. Woogler

    Woogler

    Joined:
    Jun 3, 2015
    Posts:
    2
    Hello.
    I am creating a model for research.
    I made a robot and connected to computer through UART Protocol.
    What I want to do is using robot's velocity to move the camera object in Unity 3D Space.
    So, I thought that it may work if unity can read the text file which is written by console application made from C.
    I searched a lot, I couldn't find about how to read text real-time in Unity.
    But, I found some function "Resources.load" and uses it in Update Function in Camera Controller script file.
    Unfortunately, there is a error. I think this error is so easy to fix. But I'm not used to coding in Unity.
    And I guess that it may have a problem about time.

    Here is the code:
    public class CameraController : MonoBehaviour {

    public TextAsset textFile;
    string tmps;
    StringReader read = null;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
    transform.Translate (new Vector3 (0, 0, 1) * Time.deltaTime);
    textFile = (TextAsset)Resources.Load ("/test.txt");
    read = new StringReader (textFile.text);
    if (read == null) {
    GetComponent<TextMesh>().text ="not found";
    } else {
    tmps = read.ReadLine ();
    GetComponent<TextMesh>().text = tmps;
    }
    }
    }

    And this is the error.
    NullReferenceException: Object reference not set to an instance of an object
    CameraController.Update () (at Assets/Scripts/CameraController.cs:20)

    I'm sorry to ask about it in this forum. I know about the UnityAnswers and tried to post it.
    But, Moderator haven't post it yet and i don't have much time to do it.
    Frankly, I have to solve this problem unile tomorrow.
    Please, Help...
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    your text file should be in

    <your project>\Assets\Resources\

    and the string you pass into Resources.Load doesn't need the "/"


    also, can you use [ code] [ /code] tags when pasting code into the forums, helps with the readability and put in line numbers so we can see which line the error is complaining about. :D
     
  3. dterbeest

    dterbeest

    Joined:
    Mar 23, 2012
    Posts:
    389
    and.. don't use the .txt extension (Resource.Load don't need no file extension)
     
  4. ThomasCreate

    ThomasCreate

    Joined:
    Feb 23, 2015
    Posts:
    81
    You can just use regular .NET methods of reading text files, there is no need to use Resources.Load or TextAssets.
     
  5. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    system file method can have issues when you build to the various platforms and you can also run into file path issues too... but yes you can use it :p
     
  6. ThomasCreate

    ThomasCreate

    Joined:
    Feb 23, 2015
    Posts:
    81
    He's clearly not looking for a cross platform implementation, and if he's using as hacky a method as writing to and reading from a text file to communicate between programs, I'm sure file path issues aren't going to be a problem either. :3
     
  7. Woogler

    Woogler

    Joined:
    Jun 3, 2015
    Posts:
    2
    Thanks, Everyone!
    I have a problem about data path actually.
    ThomasCreate, You're right. I'm not professional programmer.
    I just want to implement the simulation. I will give more information.
    My goal is synchronize the robot's moving to camera's moving in 3D Space.
    My team members have already done to make a robot and send the signal about robot's moving by UART.
    Actually, I have to use that signal for camera's moving. But I don't know how to do that.
    I'm very newbie.
    So, I proposed to the member to convert a signal to text file using MFC File I/O.
    And I thought that if I succeed to read that every frame or second, then
    I can move the camera objects using transform.translate function.
    However, Problem is that I think Resource.Load function should use before build!
    You know, after I build the scene, then Unity makes .exe file and (MyProject)_Data folder not assets folder.
    I found that (MyProject)_Data folder have resources folder But many webpage talks about resources folder in assets which can be shown when we make project with Unity 5.
    Does Resources.load relate to the Resources folder in _Data folder after build?
    And Could Resources.load function be used in Update() in CameraController for reading file every frame?
    I cannot find information about that because many people just external text file by loading saved data not loading data refreshed by some other program.
     
  8. ThomasCreate

    ThomasCreate

    Joined:
    Feb 23, 2015
    Posts:
    81
    Since the robot is sending data over UART, it is possible to read that data using the .NET SerialPort class within Unity. I've done that myself for communicating with an Arduino robot.

    Basically, you find which COM port the robot is associated with (check the device manager in Windows) and open a SerialPort instance with it. Then you can start checking if there is any data inside the serial buffer - normally you can use the DataReceived event, but the Mono version Unity is using doesn't support this. You could do a Read() on the port in the Update loop instead, but because that's a blocking call it creates a lot of lag. Instead, you should run your own polling thread and have it send the data over to the main thread. Your team members will be able to tell you what the robot is sending out so you can make sense of the binary information in the serial buffer.

    I'll see if I can dig up a code sample so my explanation makes some more sense.

    EDIT: Here, I hope this'll help. You would replace LatestButtonPress with the positioning data of your robot. A script on the camera will then access this property and use it to position itself. Depending on how the robot measures its position, you might need to calculate the median value of the input to get rid out erroneous readings.

    Also, you have to change the .NET settings in Project > Player > Other settings to .NET 2.0, instead of the subset.

    Code (CSharp):
    1. public class SerialComms
    2. {
    3.     private const string PORT = "COM3";
    4.     private SerialPort _port;
    5.     private const int POLLING_DELAY = 50;
    6.  
    7.     public int LatestButtonPress { get; set; }
    8.  
    9.     private bool _runThread = true;
    10.  
    11.     public SerialComms()
    12.     {
    13.         LatestButtonPress = -1;
    14.  
    15.         _port = new SerialPort(PORT, 9600);
    16.         _port.Open();
    17.  
    18.         Thread pollingThread = new Thread(RunPollingThread) { IsBackground = true };
    19.         pollingThread.Start();
    20.     }
    21.  
    22.     public void Stop()
    23.     {
    24.         _runThread = false;
    25.         _port.Close();
    26.     }
    27.  
    28.     private void RunPollingThread()
    29.     {
    30.         while (_runThread)
    31.         {
    32.             PollArduino();
    33.  
    34.             Thread.Sleep(POLLING_DELAY);
    35.         }
    36.     }
    37.  
    38.     private void PollArduino()
    39.     {
    40.         if (!_port.IsOpen)
    41.             return;
    42.  
    43.         string line = _port.ReadLine();
    44.         if (string.IsNullOrEmpty(line))
    45.             return;
    46.  
    47.         LatestButtonPress = int.Parse(line);
    48.     }
    49. }
     
    Last edited: Jun 5, 2015