weapon visibility script

Hi

Im working on a tool swap script and I want to be able to place this script onto my weapons group and have it affect the visibilty of all my weapons that are under this group.

I have coded this before however since a version jump it doesn’t seem to work anymore.

The way in which I am evoking the visibility is by declaring all of the weapons that im placing in the weapons group as game objects

and using the GameObject = GameObject.Find functions to locate the weapons.

using UnityEngine;
using System.Collections;

public class Weapon_equipment_swap2 : MonoBehaviour {
	
	
	
	
	GameObject metal_detector;

	
	void Awake () 

		{
	
		  GameObject metal_detector =  GameObject.Find("FirstPerson 						Controller/Main_Camera/metal_detector");
		
		}
	
	void Update () {
	
		
		
		if(Input.GetKeyDown(KeyCode.Alpha1))
			
		{ 
		metal_detector.renderer.enabled = true;
		}

However when I do this I get a Null reference exception error which obviously means it can’t find the object.

So my question is how can evoke the visibility of all of my weapons without attaching any direct scripts to them but rather attaching one “master script” (if you like) to the group that contains all my weapons and handles the visibility from there?

Two things:

  1. Make sure your gameobject names are correct (it seems you have some spaces in there...)
  2. .renderer is only valid for a Renderer on this GameObject and not for other Renderers on child objects.

You can either deactivate the child-GameObjects with SetActiveRecursively or if you just want to deactivate the Renderers do it that way:

Renderer[] allChildRenderers = metal_detector.GetComponentsInChildren<Renderer>();
foreach (Renderer R in allChildRenderers)
{
    R.enabled = false;
}

edit

ps. You shouldn’t use Find in Awake, use Start instead. Awake is called from the constructor of your script. At this time other objects might haven’t been created yet.