0
NullReferenceException: Object reference not set to an instance of an object
WaypointSystem.Update () (at Assets/Move/WaypointSystem.cs:41)

Ошибка но Unity запускается. Почему так ?

41 строка это :

if (tem.Length > 0) {

передней :

Transform[] tem = newChildPath.GetComponentsInChildren(typeof(Transform), true) as Transform[];

сам код:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

[ExecuteInEditMode]

public class Quest {
    public int variantdataid,obvpid,xdid,uid;
    public float  x,y,h;
}

public class WaypointSystem : MonoBehaviour {

    public List<Transform> waypoints = new List<Transform> ();
    int index = 0;
    public GameObject newChildPath;
    public List<Quest> quests = new List<Quest>();

    public bool disableInGame;
    Transform _transform;
    GameObject _gameObject;
    void Start ()
    {
        ReadCSVFile ();
        _transform = transform.root;
        _gameObject = _transform.gameObject;
        newChildPath = new GameObject("Path");
        newChildPath.transform.parent = transform;

        for (int i=0;i<quests.Count;i++)
        {
            GameObject newChildPathWay = new GameObject("Way"+i);
            newChildPathWay.transform.parent = newChildPath.transform;
            newChildPath.transform.localPosition = new Vector3(-(float)quests[i].x+6257974f, -186.84f, -(float)quests[i].y+8377535f);
        }
    }

    void Update () {
        Transform[] tem = newChildPath.GetComponentsInChildren(typeof(Transform), true) as Transform[];
        if (tem.Length > 0) {
            waypoints.Clear ();
            index = 0;
            foreach (Transform t in tem) {
                if (t != transform) {
                    t.name = "Way " + index.ToString ();
                    waypoints.Add (t);
                    index++;
                }
            }
        }
    }

    void OnDrawGizmos()
    {
//      Gizmos.color = Color.yellow ;
//      Gizmos.DrawSphere (transform.position, 1);
        if (waypoints.Count > 0) {
            Gizmos.color = Color.green;
            foreach (Transform t in waypoints)
                Gizmos.DrawSphere (t.position, 1f);
            Gizmos.color = Color.green;
            for (int a = 0; a < waypoints.Count - 1; a++)
            {
                Gizmos.DrawLine (waypoints[a].position, waypoints [a + 1].position);
            }
        }
    }

    public void ReadCSVFile ()
    {
        TextAsset questdata = Resources.Load<TextAsset> ("movie_realposition");
        string[] data = questdata.text.Split (new char[]{'\n'});
        for(int i=1;i<data.Length-1;i++) {
            string[] row = data [i].Split (new char[]{';'});
            Quest q = new Quest ();
            float.TryParse (row[4], out q.x);
            float.TryParse (row[5], out q.y);
            quests.Add(q);
        }
    }
}
  • Очевидно tem = null – Алексей Шиманский Jun 09 '19 at 13:32
  • Наверное потому что исключение где то перхвачено – tym32167 Jun 09 '19 at 13:37
  • похоже, as Transform[] не может преобразовать тот объект или таких объектов GetComponentsInChildren не находит. посмотри, нет ли generic-версии этого или похожего метода – dgzargo Jun 09 '19 at 13:41
  • @tym32167 Я буквально второй день изучаю Unity и пока не понимаю как это можно исправить – Ivan Triumphov Jun 09 '19 at 13:43
  • @dgzargo есть GetComponent – Ivan Triumphov Jun 09 '19 at 13:45
  • @СергейМишин if(tem != null) поставил проверку, но теперь не отрабатывает OnDrawGizmos(). В точках шары не рисует и не проводятся линии между шарами – Ivan Triumphov Jun 09 '19 at 14:02
  • @IvanTriumphov очевидно потому, что tem всегда null. И нужно смотреть почему. Например GetComponentsInChildren ничего не находит. Включить Отладку и посмотреть с самого начала что есть в newChildPath и т.д. и есть у меня ощущение, что надо было писать не newChildPath = new GameObject("Path"), а что-то типа newChildPath = GameObject.Find("Path"); (https://docs.unity3d.com/ScriptReference/GameObject.Find.html) или что-то подобное – Алексей Шиманский Jun 09 '19 at 15:42
  • @СергейМишин GameObject.Find("Path"); А такое же не будет работать. Потому что у меня создаётся new GameObject("Path"); в void Start () – Ivan Triumphov Jun 09 '19 at 16:40
  • @СергейМишин в начале в функции void Start () создать Path и его дочернии элементы, а потом вместо этих GameObject нарисовать сферы и пути между ними – Ivan Triumphov Jun 09 '19 at 16:46
  • во первых нужно инициализировать массив Transform[] tem = new Transform[кол-во элементов]

    во вторых вы это все делаете в апдейте..каждый кадр, это как минимум не оптимально

    – animagnoa Jun 10 '19 at 03:59

0 Answers0