-2

I am trying to add a randomly generated transform to a list. Doing the following gives me a runtime error saying NullReferenceException at the 5th line. What am I doing wrong? Also is there a better way to add a Transform to a list? Sorry if I made any mistakes as this is my first time on Stack Overflow.

start()
{
  GameObject createdObject = new GameObject();
  createdObject.transform.position = new Vector3(5f, 5f, 5f);
  waypoints.Add(createdObject.transform);
}
  • I would expect that if they all have the same parent, then you can just transform the parent. Otherwise you're probably looking at a loop: _for each waypoint in the list_ ... _transform that waypoint_. – Wyck Sep 27 '22 at 14:46
  • No, I mean the waypoints.Add line gives me a NullReferenceException – Charan Vendra Sep 27 '22 at 14:49
  • `waypoints` is null? That seems like [your first problem](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). – Wyck Sep 27 '22 at 14:58

1 Answers1

1

I fixed it, Thanks to @Wyck.

Previously:

    private List<Transform> waypoints;

Changed to:

    private List<Transform> waypoints = new List<Transform>();
  • 1
    Since this is your first time on Stack Overflow, I'll let you know that we don't need this answer here. Yours is a duplicate question. And if you had searched the web for NullReferenceException you likely would have found that information. NullReferenceExceptions are well understood problems with C# programs. This post is not the place that people should be coming to for that information. I'm glad you fixed your problem though. But when you have a null reference exception, the way to remedy the problem is well established and discussed already elsewhere on this site. – Wyck Sep 27 '22 at 15:11