- Home /
List Transform returns null
In Start I add a GameObject and a Transform to the RCList. In the Start Debug.Log it returns the transform just fine but in the update method when I try to access the transform from the list it returns null.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RollercoasterBuilder : MonoBehaviour
{
public List<RCList> RollercoastersList = new List<RCList>();
public GameObject straightTrackForward;
void Start()
{
GameObject newTrack = Instantiate(straightTrackForward, straightTrackForward.transform.position, transform.rotation);
newTrack.name = "track1";
Transform newTrackTransform = newTrack.GetComponent<Transform>();
Debug.Log(newTrackTransform);
RollercoastersList.Add(new RCList(newTrack, newTrackTransform));
}
void Update()
{
Debug.Log(RollercoastersList[0].tF);
}...
List Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RCList
{
public GameObject gO;
public Transform tF;
public RCList(GameObject newTf, Transform newTF)
{
newTf = gO;
newTF = tF;
}
}
Answer by jmhoubre · Jul 22, 2020 at 09:37 AM
Hello,
I think you have reversed newTf and gO in the constructor.
Good luck (sorry for any English mistakes).
Answer by Bunny83 · Jul 22, 2020 at 10:40 AM
Your constructor makes no sense on multiple levels:
public RCList(GameObject newTf, Transform newTF)
{
newTf = gO;
newTF = tF;
}
First there are your horrible and misleading variable names. Second you have your assignments the wrong way around. You assign your class variables to the local parameter variables. Therefore you never actually initialize your class variables.
Apart from that I don't really see the point of your "RCList" at all. Why do you store the transform component and the gameobject? Just storing the transform component would be way simpler and doesn't really have any downsides.