Reputation: 2724
I'm trying to access the text component of my TextMesh from a class that is the Grand parent of my text mesh object.
I've been playing around with this code but can't get it to change. What is it that I'm doing wrong? Is there an extra call or something I need to make?
This is code is held on my grandparent object (in this case a camera), plane is the direct child of the camera which is just a plane object and is called Plane and the textmesh is the child of my plane object. The text mesh is called FloorMenu.
TextMesh text = (TextMesh)GameObject.Find("Plane").GetComponent("FloorMenu");
text.text = "test";
When I try to run this code I get the following error which when double clicked, points me to the text.text
line:
NullReferenceException: Object reference not set to an instance of an object
As far as I'm aware the first line should be pointing to the TextMesh dealing with the given error. Though since I am getting the error, I must be doing something wrong.
Could someone please educate as to what I'm doing wrong?
Upvotes: 0
Views: 3109
Reputation: 4195
The way you've assembled that line of code prevents you from seeing which part of it is throwing the NullReferenceException.
// Note: This is C#
var plane = GameObject.Find("Plane");
var floorMenu = plane.GetComponent("FloorMenu"); // <-- FYI: GetComponent("FloorMenu") seems wrong (probably null).
// var floorMenu = plane.GetComponent(typeof(TextMesh)); // this might work, depends on how your scene is structured.
Debug.Log("is a TextMesh?: " + (floorMenu is TextMesh)); // Bet you this is false.
var text = (TextMesh) floorMenu;
text.text = "test";
Upvotes: 0