- Home /
Hide/Show GameObject from script
So here's my dilema. I am trying to display a hat (The game object is called "Party" because it is a party hat) on my character by having the player click a button in a menu that sets the hat's renderer to true. The hat is a child of my 2d character and the hat's sprite renderer's check box is unchecked (which I am assuming means that the renderer is false). When I run the game and click the button in the menu, Unity gives me an error saying "Object reference not set to an instance of an object" and the hat does not display in game. Here's my script: using UnityEngine; using System.Collections;
public class HatSelectMenu : MonoBehaviour {
private GameObject party;
// Use this for initialization
void Start () {
party = GameObject.Find("Party");
}
// Update is called once per frame
void OnGUI () {
if(GUI.Button (new Rect(Screen.width / 2 - 50, Screen.height / 2 + 20, 200, 75), "Show Hat"))
{
party.renderer.enabled = true;
}
if(GUI.Button (new Rect(Screen.width / 2 - 30, Screen.height / 2, 100, 50), "Main Menu"))
{
Application.LoadLevel(0);
}
}
}
If you need any clarification I would be happy to help.
I assume you know that it can't find the GameObject "Party", right?
$$anonymous$$aybe you spelled "Party" as party? :P
Answer by saruul34 · Mar 15, 2014 at 04:43 PM
using UnityEngine;
using System.Collections;
public class HatSelectMenu : MonoBehaviour {
public GameObject party; // Drag here party hat gameobject.
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnGUI () {
if(GUI.Button (new Rect(Screen.width / 2 - 50, Screen.height / 2 + 20, 200, 75), "Show Hat"))
{
if(party.activeSelf)
party.SetActive(true);
if(party.renderer)
party.renderer.enabled = true;
else print("Where is my hat?");
}
if(GUI.Button (new Rect(Screen.width / 2 - 30, Screen.height / 2, 100, 50), "Main Menu"))
{
Application.LoadLevel(0);
}
}
}
This works but it displays the buttons in the game scene. I wanted to have the buttons in my main menu of sorts...
I tried this code. But it's not working. There is no error but it prints where is my hat? Why?
Answer by mclankyman · Mar 15, 2014 at 03:05 PM
Check your casing. And maybe tag your hat with "Hat" and use
party = GameObject.FindGameObjectWithTag("Hat");
Okay, I tagged it but I still get the error mentioned in my original statement. When I click on the error Unity highlights the party.renderer.enabled = true;
snippet, so I am assu$$anonymous$$g that that is where the problem is.