1. Home
  2. Docs
  3. Advanced Concepts
  4. Streaming Data

Streaming Data

In some cases we would like to stream data to the chart, rather then just having static data. Streaming with the new data series chart is very simple. You may want to have a look at “Extras/Example Scenes/Continuous Streaming” and “Extras/Example Scenes/Multiple Charts”

How to script a streaming chart

in a similar way to the quick start tutorial, set up a chart and a data loader script. This time we will use the Update method to append points to the chart. Have a look at the following script

    public DataSeriesChart chart; // set this from the unity inspector
    public double TotalPoints = 100000;  // total point count
    void Start()
    {
        var data = chart.DataSource.GetCategory("dataseries-1").Data; //get the category data object 
        data.Clear(); // clear the category
    }

    double x =0;
    // Update is called once per frame
    void Update()
    {        
        if (x < TotalPoints)
        { 
            var data = chart.DataSource.GetCategory("dataseries-1").Data; // get the category data
            data.Append(x, Random.Range(-5f, 5f)); // append a random point
            x++; // increase current position
        }            
    }

continuous streaming

In some use cases , you may want to stream data over a long period of time. in this case it is important to clean points from the graph to conserve memory. You can do that by calling the method ‘RemoveAllBefore’. This method removes all points before a specified x value. you can use the edge of the view in order to remove all points that are out of view. This is the code from
“Extras/Example Scenes/Continuous Streaming”

    void Update()
    {
        var data = chart.DataSource.GetCategory("cat12").Data; // get the catgory data
        for (int i = 0; i < PointsPerFrame; i++) // for each point per frame
        {
            y = Mathf.Clamp((float)y + Random.Range(-0.05f, 0.05f), 0f, 10f); // get a random value
            data.Append(x, y); // append the point
            x++;
        }
        if (data.Count > MaxPoints) // if the amount of points in the chart is larger then the maximum
            data.RemoveAllBefore(chart.Axis.View.HorizontalViewStart); // remove all points that are before the beginning of the view portion.
    }