Example_DynamicChart.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using UnityEngine;
  2. using XCharts.Runtime;
  3. namespace XCharts.Example
  4. {
  5. [DisallowMultipleComponent]
  6. public class Example_DynamicChart : MonoBehaviour
  7. {
  8. BaseChart chart;
  9. void Awake() { }
  10. void Update()
  11. {
  12. if (Input.GetKeyDown(KeyCode.Space))
  13. {
  14. AddPieChart("Dynamic PieChart");
  15. }
  16. if (Input.GetKeyDown(KeyCode.L))
  17. {
  18. AddLineChart("Dynamic LineChart");
  19. }
  20. }
  21. GameObject CreateChartObject(string chartName)
  22. {
  23. for (int i = transform.childCount - 1; i >= 0; i--)
  24. {
  25. Destroy(transform.GetChild(i).gameObject);
  26. }
  27. var chartObject = new GameObject();
  28. chartObject.name = chartName;
  29. chartObject.transform.SetParent(transform);
  30. chartObject.transform.localScale = Vector3.one;
  31. chartObject.transform.localPosition = Vector3.zero;
  32. return chartObject;
  33. }
  34. void AddPieChart(string chartName)
  35. {
  36. var chartObject = CreateChartObject(chartName);
  37. var chart = chartObject.AddComponent<PieChart>();
  38. chart.Init();
  39. chart.SetSize(580, 300);
  40. chart.GetOrAddChartComponent<Title>().show = true;
  41. chart.GetOrAddChartComponent<Title>().text = chartName;
  42. chart.GetOrAddChartComponent<Tooltip>().show = true;
  43. chart.GetOrAddChartComponent<Legend>().show = true;
  44. chart.RemoveData();
  45. chart.AddSerie<Pie>();
  46. for (int i = 0; i < 3; i++)
  47. {
  48. chart.AddData(0, Random.Range(10, 20), "pie" + (i + 1));
  49. }
  50. }
  51. void AddLineChart(string chartName)
  52. {
  53. var chartObject = CreateChartObject(chartName);
  54. var chart = chartObject.AddComponent<PieChart>();
  55. chart.Init();
  56. chart.SetSize(580, 300);
  57. chart.GetOrAddChartComponent<Title>().show = true;
  58. chart.GetOrAddChartComponent<Title>().text = chartName;
  59. chart.GetOrAddChartComponent<Legend>().show = false;
  60. var tooltip = chart.GetOrAddChartComponent<Tooltip>();
  61. tooltip.trigger = Tooltip.Trigger.Axis;
  62. var xAxis = chart.GetOrAddChartComponent<XAxis>();
  63. var yAxis = chart.GetOrAddChartComponent<YAxis>();
  64. xAxis.splitNumber = 10;
  65. xAxis.boundaryGap = true;
  66. xAxis.show = true;
  67. yAxis.show = true;
  68. xAxis.type = Axis.AxisType.Category;
  69. yAxis.type = Axis.AxisType.Value;
  70. chart.RemoveData();
  71. chart.AddSerie<Line>();
  72. for (int i = 0; i < 10; i++)
  73. {
  74. chart.AddXAxisData("x" + (i + 1));
  75. chart.AddData(0, Random.Range(10, 100));
  76. }
  77. }
  78. }
  79. }