what is the problem with this code?

using UnityEngine;
using System.Collections;

public class TestCullMesh : MonoBehaviour {

private GameObject playerCar ;
public Material[] myMaterials ;

void Start () {
	playerCar = GameObject.FindGameObjectWithTag("Player");
	myMaterials = gameObject.renderer.materials ;
}

void Update () {
	if ( Vector3.Distance(playerCar.transform.position, transform.position) < 20) {	
			if(!gameObject.GetComponent(typeof(MeshRenderer))){
				gameObject.AddComponent(typeof(MeshRenderer));
				gameObject.renderer.materials = myMaterials ;
				}
	}
	else{GameObject.Destroy(gameObject.GetComponent("MeshRenderer")); }
}

}

Unless you give more info as to what made you ask, this is as best as it gets.

“what is the problem with this code?”

  1. playerCar =
    GameObject.FindGameObjectWithTag(“Player”);

    If you can assign the playerCar
    via the inspector and not having to
    search for it and finding it in your
    scene, that would be great!
    (performance-wise)

  2. if (
    Vector3.Distance(playerCar.transform.position,
    transform.position) < 20)

    Two things I don’t like about this:

    1. Don’t use hard-coded values, store
      20 in a variable instead, and then
      use it in your code.
    2. If you wanna compare the distance
      between two points, it’s better to
      compare the squares of the distances
      instead of the real distance which
      involves a square root operation,
      which is a bit expensive.

    if ((pos1 - pos2).sqrMagnitude <
    myDist * myDist)
    // do something

  3. Disable/Enable your mesh renderer
    instead of Destroying and
    re-instantiating it.

  4. Lastly, if you’re not using anything
    from System.Collection namespace,
    remove it.

Based on the information you’ve given you have two options to manage your memory.

  1. Reuse your gameobjects (instead of removing components and adding them, move whole child game objects) so if you have a collection of maximum trees that can be in view move them to a pool when they go out of view and from there into the correct location as it comes into view.

  2. Use sub scenes and load / unload them…this of course depends on the size of the levels as to if this would work for you.

I think they are your best options but it really depends on the scope of your game.