Editor reference vs GetComponent<>()

I noticed you have a preference for Editor references over GetComponent<>() calls in Awake() - I imagine there must be some performance benefit.

But then I wondered why you chose to use GetComponent() to get the GridSystemVisualSingle when you could avoid the call by directly instantiating the component (rather than its transform).

I realize we’d need a different editor reference here for the GridSystemVisualSingle. We could use the Awake() method to get its transform so that we can also have that cached if we expect to use the transform later on in the lesson.

Sorry for all the questions, but I’m trying to understand why certain design choices were made and if there’s some higher level principle you’re applying. I’ll post a separate question re: overall system design because I have questions there too.

Neither GetComponent or [SerializeField] references are in and of themselves bad. Some programmers prefer one over the other.

In terms of the GridSystemVisualSingle choice , this is likely due to a limitation in the Unity Editor when it comes to linking Assets as [SerializeField] references. When linking with components that are on the same GameObject as the script, one can easily drag the component into the reference, and Unity takes care of everything. If, on the other hand, you are linking to a prefab, then unless the reference is a built in Unity component, it simply won’t show up in the Chooser. This means locating the reference manually and dragging it into the inspector.

1 Like

Ok thanks. I don’t remember encountering an issue you describe but good to know it can happen and what to do about it.

I ended up solving it this way, using an Editor reference for prefab (vs transform) and avoiding the GetComponent() call. Seemed to work just fine.

public class GridSystemVisual : MonoBehaviour
{
    public static GridSystemVisual Instance { get; private set; }

    // using an editor reference for the Prefab vs the transform
    [SerializeField] private GridSystemVisualSingle gridSystemVisualPrefab;

    private GridSystemVisualSingle[,] gridSystemVisualSingleArray;

    private void Start()
    {
        gridSystemVisualSingleArray = new GridSystemVisualSingle[
            LevelGrid.Instance.GetWidth(),
            LevelGrid.Instance.GetHeight()
        ];
        for (int x = 0; x < LevelGrid.Instance.GetWidth(); x++)
        {
            for (int z = 0; z < LevelGrid.Instance.GetHeight(); z++)
            {
                GridPosition gridPosition = new GridPosition(x, z);
                // avoids GetComponent call by directly instantiating GridSystemVisualSingle objects
                gridSystemVisualSingleArray[x,z] = Instantiate(gridSystemVisualPrefab, LevelGrid.Instance.GetWorldPosition(gridPosition), Quaternion.identity);
            }
        }
    }

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms