- Home /
simple invisibility
Hi Im using c# was just wondering why a simple effect like toggling off my visibility won't work.
I think it must be me just being really dense and missing something really simple.
Have written the following script and attached it to my cube.
Whenever I load up my game I get a null reference error and the warning
Warning CS0649: Field 'test.Cube' is never assigned to, and will always have its default value null (CS0649) (Assembly-CSharp)
I don't really know what it means by assigned to either usually when I get null references it's because I haven't declared an object etc have done visibility before aswell and looked at my other code which is the same evokes visibility or invisibility by using the objects.renderer.enabled function.
Where have I messed up?
using UnityEngine; using System.Collections;
public class test : MonoBehaviour {
GameObject Cube;
void Awake ()
{
GameObject Cube = GameObject.Find("Cube");
}
// Update is called once per frame
void OnGUI () {
if(Event.current.type == EventType.keyUp && Event.current.keyCode == KeyCode.F1)
{
Cube.renderer.enabled = false;
print("working");
}
}
}
Being never assigned means that when it reads the input, your GameObject Cube is null and there is no renderer to set false.
Try GameObject.FindGameObjectWithTag("Cube") ins$$anonymous$$d of GameObject.Find("Cube") and put the "Cube" tag on your Cube obviously!
Why are you even using GameObject.Find
to find your cube when the script is attached to it? Use transform.renderer.enabled
ins$$anonymous$$d. Also, take it ouf of OnGUI
and into Update
. You're not using any GUI elements and it causes garbage collector issues.
Just renderer.enabled
is sufficient, you don't need transform.renderer.enabled
. There isn't a FindGameObjectWithTag command, but FindWithTag isn't a substitute for Find anyway, they do two different things.
Answer by Eric5h5 · Oct 17, 2011 at 07:18 PM
You never use the "Cube" variable. Instead you have another local variable defined in Awake, but you never use that either. But as asafsitner mentioned, you don't need to use Find if the script is already attached to the object you want to work with.
As an aside, you'd be better off following the convention of using lowercase for variable names and uppercase for class names. Also, please format your code properly when posting, it takes two seconds.
Thanks guys will get on it and apologies for not formatting code im still quite new to code but will do that in future as well when adressing a problem.
Your answer
Follow this Question
Related Questions
How do I see a Configurable Joint in the Scene Window? 0 Answers
Mouse Over Visibility 1 Answer
How can I get the lowest position of objects that are visible by the camera? 1 Answer
Hide cursor and stop interaction 1 Answer
Objects Appearing 1 Answer