I have been looking around for ways to add instatiated objects to lists and i found several ways to do it, but all of them have the same issue where i get a “NullReferenceException: Object reference is not set to an instance of an object” even though i literall create the instance on the same line of code as i’m adding it to the list.
public class ToggleInputNode : MonoBehaviour
{
[SerializeField] GameObject _linePrefab;
[SerializeField] float _radiusToCreateLine = 1f;
private bool _lineCreated = false;
SpriteRenderer _sr;
List _lines;
private void OnMouseDrag()
{
//Create a Line if the User drags the mouse a certain range
if (DistanceFromCenter(_radiusToCreateLine) && !_lineCreated)
{
Debug.Log(“There are " + _lines.Count + " lines”);
_lines.Add(Instantiate(_linePrefab, transform.position, Quaternion.identity));
_lineCreated = true;
}
}
private void OnMouseExit()
{
_lineCreated = false;
}
private bool DistanceFromCenter(float r)
{
//Calculate distance between the node and the mouse
Vector2 nodePos = new Vector2(transform.position.x, transform.position.y);
Vector2 mousePos = GetMousePosition();
float distance = Vector2.Distance(nodePos, mousePos);
if (distance >= r)
return true;
return false;
}