How do I assign a gameObjects Renderer component to renderer Var in var decleration?

I have 480 objects in my scene , they each use the same script , the script takes in the gameObjects Mesh Renderer… and Collider

I would have to drag and drop the GameObjects into the the inspector 480 times or assign them by code .
it is a very slow process. and assigning colliders and renderers would drastically slow the game .

umm something like this

though this method does not work

public  MeshCollider _MeshCollider = this.GetComponent<Collider>();
	public  MeshRenderer _MeshRenderer = this.GetComponent<MeshRenderer>();

You can’t! :slight_smile:

I answered a similar question a little while ago: Why am i getting NullReferenceException? - Unity Answers

The upshot of it is that those bits of code after the variable declarations get executed immediately after the object is created in memory. However things like unity components or any data setup in the inspector are not set up at that point. If you imagine the process of creating one of your game objects, internally it goes:

  • object is allocated in memory - at this point it is totally blank, with all your members at their defaults (i.e. 0s)
  • next, your ‘construction code’ is executed, which includes the bits of code after your variable declarations
  • now unity kicks in and sets up the extra bits - it creates components, pokes in values for stuff from the inspector and generally turns your allocated object into something that works in the game
  • finally, unity calls ‘Start’ on your object, if it exists

The upshot is that you can’t do anything other than very simple initialisation of variables when declaring them (like var myval = 10). Anything that references unity bits and pieces, or any other objects for that matter, should be done inside the Start function.

So your code might look like:

MeshCollider _MeshCollider;
MeshRenderer _MeshRenderer;

void Start()
{
    _MeshCollider = GetComponent<MeshCollider>();
    _MeshRenderer = GetComponent<MeshRenderer>();
}

Just remember - anything other than simple setting of values to constants should be done in the Start function.

-Chris