Public renderer not saving during Play mode

I am new to Unity 3d, and am having a problem with the renderer component not saving during Play mode.

While I am in Edit mode the prefab that I want to render shows up in the inspector. When I enter Play mode the renderer component gets removed from the scrip. When I go back to Edit mode the renderer gets added back. (In Play mode, if I move the prefab to the public renderer then, my script does what I want it to.)

84187-unitypng.png

I want the inspector to stop forgetting what renderer to use.

what am I doing wrong here?

{
	public GameObject RoadPrefab;
	GameObject RoadPrefabClone;
	public Material[] MyMaterials;
	public Renderer roadPrefabsRend;
	private int index = -1;

	void Start(){
		roadPrefabsRend = GetComponentInChildren<Renderer>();
		roadPrefabsRend.enabled = true;
	}
		
	void Update() {
		RoadPrefabClone = Instantiate(RoadPrefab, transform.position, Quaternion.identity) as GameObject;
		roadPrefabsRend.material = MyMaterials [index=Random.Range (0,3)];
		RoadPrefabClone.transform.localScale += new Vector3(Random.Range (3, 11), 0.25f, 3); 
            Destroy(RoadPrefabClone, 10);
	}

1 Answer

1

You’re assigning a value to roadPrefabsRend in your Start method. Comment out that line or make sure that there is a Renderer component childed to the GameObject your script is attached to. Alternatively, you could do the following:

void Start() {
    if (roadPrefabRend == null) {
        roadPrefabRend = GetComponentInChildren<Renderer>();
    }
}

Or, my preference, get it lazily;

[SerializeField] Renderer _roadPrefabRenderer
Renderer RoadPrefabRenderer
{
    get
    {
        if (_roadPrefabRenderer == null) {
            _roadPrefabRenderer = GetComponentInChildren<Renderer>();
        }
        return _roadPrefabRenderer;
    }
}

And access the RoadPrefabRenderer property instead of the variable. I’ve been meaning to check how Unity handles the null coalescing operator lately, but it might be able to be condensed to:

Renderer RoadPrefabRenderer
{
    get { return _roadPrefabRenderer ?? (_roadPrefabRenderer = GetComponentInChildren<Renderer>()); }
}

Thanks iwaldrop! I used changed the start function and it works now.