Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity3d MeshRender

Tags:

c#

unity3d

I'm trying to use C# to disable and enable the MeshRender component in Unity3d however I am getting the following error,

error CS0120: An object reference is required to access non-static member `UnityEngine.GameObject.GetComponent(System.Type)'

The line of code I am using is below. I'm using this in the same function.

MeshRenderer showZone = GameObject.GetComponent<MeshRenderer>();

Also I'm posting here rather than Unity Answers as I get a far faster response here and it's always useful information regardless of the outcome.

like image 896
Jack Miller Avatar asked Jun 15 '14 16:06

Jack Miller


1 Answers

You're having trouble with several problems. First, you are trying to use GetComponent<> on a class instead of an instance of an object. This leads directly to your second problem. After searching for a specific GameObject you're not using the result and you're trying to disable the renderer of the GameObject containing the script. Third, C# is case-sensitive, Renderer is a class while renderer is a reference to an instance of Renderer attached to the GameObject

This code snippet combines everything: find the GameObject and disable its renderer

GameObject go = GameObject.FindWithTag("zone1");
if (go != null) { // the result could be null if no matching GameObject is found
  go.renderer.enabled = false;
}

You could use go.GetComponent<MeshRenderer>().enabled = false; instead of go.renderer. enabled = false; But by using renderer you don't need to know what kind of renderer is used by the GameObject. It could be a MeshRenderer or a SpriteRenderer for example, renderer always points to the renderer used by the GameObject, if there exists one.

like image 185
Stefan Hoffmann Avatar answered Oct 11 '22 12:10

Stefan Hoffmann