- Home /
Receiving String from Variable in other Object
Original Question:
k before you say, there are loads of topics about this.
I know.. there are about 600 on just the NullRefference issue.
And i ofcourse dont wanna add questions that aren't usefull to the question database.
The thing is. they honestly didn't work for me. or i have looked exactly at 10 wrong versions?
i want to grow as a unity coder/designer. So i need to understand this.
I also want to turn this question into something quick and useful for others to read once i get this working. :)
I understand that NULL bassicly means that theres no data to give. So i need to define where it has to get the info. in my case i think its because my script is inside a object called "Player2" thats what i think atleast.. anyways here is how simple my code is.
They are two seperate scripts each in there own object. one is in a cube named "Player2" the other is in a mesh text object named "New Text"
using UnityEngine;
using System.Collections;
public class Player_Controller : MonoBehaviour {
public float direction;
public string Str_direction;
//public string test_if_works = "working";
void Update () {
direction = Input.GetAxis("Horizontal");
if (direction < 0.0)
Str_direction = "left";
//print("test"+printresult);
if(direction > 0.0)
Str_direction = "right";
//print("test"+printresult);
if(direction == 0.0)
Str_direction = "stationary";
//print("test"+printresult);
}
}
using UnityEngine;
using System.Collections;
public class FloatingTextSimple : MonoBehaviour {
public GameObject Player2;
private Player_Controller Player_Controller_taken;
void Start () {
Player_Controller_taken = Player2.GetComponent<Player_Controller>();
}
void Update () {
//string newdir = transform.Find("player2").GetComponent<Player_Controller>().Str_direction();
GetComponent<TextMesh>().text = Player_Controller_taken.Str_direction;
}
}
Now the code might look a bit odd. But i tried hundreds of things. And i constantly get NULLRefference errors or different types of erros. But the way i have it now seems to give the least errors atleast..
What am i trying to achieve? I am trying to display the debug text ingame on text mesh.
Why use text mesh? Because i read somewhere that its easier and less code (only a few lines)
I think im not understanding the fundamentals. And i would like to ask ontop of this question if somebody can teach me a method where i can learn this easier myself. i one time found a youtube video who did this but i lost it. The unity script reference docs are very confusing to me. They dont explain the core or something for me. but i might be missing that core. And so many tutorials on youtube they go.. ok this part of code just copy paste.. and im like.. Thats the tutorial?? Copy pasting code? how about understanding it...
'''The Error Message''' (leads to my mesh text script) NullReferenceException: Object reference not set to an instance of an object FloatingTextSimple.Update () (at Assets/Scripts/FloatingTextSimple.cs:16)
What's the full text of the error? I'll walk you through how to understand and diagnose that error if you want
Also, I'm assu$$anonymous$$g that this is actually two scripts right?
O sorry perchik, I thought i had added the error. Here you go:
NullReferenceException: Object reference not set to an instance of an object FloatingTextSimple.Update () (at Assets/Scripts/FloatingTextSimple.cs:16)
i have also edited my question explaining the objects and there scripts. + added the error.
Since this questions is about null reference exceptions, here is my explanation of what they are and how to go about fixing them.
Hey Jamora, Yes i have seen that post before. Nice post. :) It did not get me to the solution though. I think because it is very wide and spread informative. but good on its own of course.
Answer by OP_toss · Mar 05, 2014 at 07:09 PM
NullReference errors are one of the easiest to track down and solve.
Basically there's 2 spots in your code where it's even possible for one to occur. Line 33, and Line 39.
To determine which is the culprit, just print out Player2 as the first line in your Start method. If null, it means your Player2 variable isn't correctly linked or set in Unity. Check the Inspector view for the object. The other one could be due to Player2 not having a "Plyaer_Controller" script on it, or due to the gameobject that "FloatingTextSimple" is attached to doesn't have a "TextMesh" on it.
Now how to improve your code... Here's some issues and coding practices that should help you if you stick to them.
Never use GetComponent and trust blindly that it will return a value. Always store the result, check if it's not null, and act accordingly.
Use coding standards for naming your variables.
Don't use underscores in class names.
Start variables lowercase and camel case them
Don't use underscores in variables unless they're all caps and therefore are constants.
If you find yourself using GetComponent in an Update loop, don't. Get it once in Start or something and store it in a variable, which you then use in your Update loop or wherever.
Don't use .Find() as it is slow
Don't use strings for multiple option cases. That's what enums are for. Make an enum of each case and switch on it when you need to test.
Hope I came across as helpful and not discouraging, as that is my intention. Criticism will be the only way you improve, so I hope this helps you become a better programmer!
As for all the na$$anonymous$$g conventions stuff, that's not really a problem, just personal preferences.
When i do
void Start () {
print(Player2);
}
the response is indeed null. but i do have the script inside there. is this because that line of code is in the meshtext ins$$anonymous$$d of the player object?
im so confused about the way this code is working inside unity. i really thought it would be simple and just a few lines to call a variable thats set public from a gameobject in the game.
Thank you so much for all the extra tips. Some of them i do not understand though. this is what i mean with that i do not understand the basis of how the code works in unity. i really wanto understand the flow and design.
Your answers do help with that though. But i just feel a bit odd to have to ask all this in here. i cant find any source that explains this "Core" of flow etc. Or im looking completely wrong?
Na$$anonymous$$g conventions should not be personal, they are widely used and adhered to. See Pep8 for ex. If you come up with your own and go to work somewhere professional, you will make it hard on other people to read your code, and vice versa. $$anonymous$$inor things are hard to match, I agree, but many of the more obvious ones are very much agreed upon.
Player2 is an instance variable of a GameObject class. It is not assigned in your script afaik. So you must go into Unity, open the Inspector pane, select the gameobject that has this script attached, and drag the gameobject that you want to the spot that says "Player2". This will assign the variable. Use this technique often in Unity.
I'm not sure what you mean by "i do have the script inside there". Defining a script/class of type "Player2" somewhere in your project will probably mess this up, as you are redefining "Player2" to mean something else now. You should research the difference between a class and an instance of a class. Almost every class you will use will actually be an instance of a class. Every monobehavior attached to a gameobject is actually creating an instance of that class. Thus you need to tell this script which instance of GameObject the variable "Player2" should be. Then you can get the component off of it.
Hope this clears it up, feel free to ask more questions. It's hard to find tutorials on code design sometimes, especially specific to an engine.
I agree that na$$anonymous$$g conventions are important, but to suggest that's the OP's problem is wrong, and the conventions you post are not necessarily conventions everywhere so they shouldn't be phrased as rules to fix a problem.
Agreed, I didn't mean to suggest that. Sorry if that's how it came across. I meant everything under the heading "Now how to improve your code..." to be suggestions to help avoid issues like this, as well as useful tid-bits any new unity programmer could benefit from.
Which conventions are not used everywhere, out of curiousity? I've seen member variables using prefixed underscores, or "m_" but beyond that most of those are normal no?
Answer by perchik · Mar 05, 2014 at 07:14 PM
First off, I think I see your problem, but I'm going to walk you through how I'd find it.
So your error says that there's a problem at FloatingTextSimple.cs line 16,
GetComponent().text = Player_Controller_taken.Str_direction;
The error says you're referencing something that doesn't exist. So look at the objects you use on that line. There's a few different objects.
First, Player_Controller_taken
You'll have to see if that's actually set to something on start:
void Start () {
Player_Controller_taken = Player2.GetComponent<Player_Controller>();
if(Player_Controller_taken == null) {
if(Player2 == null){
Debug.LogError("assign a player 2 object in the editor");
}
else{
Debug.LogError("No Player controller on Player 2");
}
}
}
If that shows an error in the debug log, then you would need to make sure that Player2 is assigned in the editor, and that the player2 object has a Player_Controller Script.
So. You've verified that there is a player controller on Player 2 and it doesn't throw an error on start.
Now, we go back to Line 16 and see that if the Player_Controller_taken is not the problem, something else is.
So you see you're accessing Player_Controller_taken.Str_direction;
Maybe that's the problem. So now we go look at the Player Controller script. It looks like, as long as Update() has ran once, Str_direction has been set....but what happens if the text script tries to access Str_direction, before it's been set to something? Who knows, so let's go ahead and set it on start, just to make sure it exists
Player_Controller.cs:
void Start(){
Str_direction="";
}
Now. If there's still an error when we run it, then we'd go back to line 16 (assuming thats where the error still is). At this point, we know that the right side of the equals works, so maybe the error is on the left side.
GetComponent()
should return the textMesh component, but perhaps that's null. We can check first:
if(GetComponent<TextMesh>()== null) Debug.LogError("no text mesh attached");
So now, if we hit that in the Debug.Log, we know that this object doesn't have a text mesh on it and that's the problem.
I like your approach of debugging. really looking for the problem then fix.
I was thinking the Str_direction before. the way i tried to fix it was to preset the variable itself in the top of the script with "stationary"
like so: public string Str_direction = "stationary";
this did not fix it.
I just added your debug code. but i am not getting the message in my console at all that i type??? strange. i even added 111111 or 222222 so i could find it easier. but i dont see it.
I do have a new error now though UnassignedReferenceException: The variable Player2 of 'FloatingTextSimple' has not been assigned. You probably need to assign the Player2 variable of the FloatingTextSimple script in the inspector. UnityEngine.GameObject.GetComponent[Player_Controller] () (at C:/BuildAgent/work/1251241231231/artifacts/EditorGenerated/UnityEngineGameObject.cs:28) FloatingTextSimple.Start () (at Assets/Scripts/FloatingTextSimple.cs:11)
why is it i cannot find the debug messages itself anywhere though?
I read again what you typed.
and saw what i answered.
curious what your response is on that! :)
Answer by Key_Less · Mar 05, 2014 at 07:40 PM
Your scripts are working fine. Your Player2 game object reference is the culprit. You are getting the null reference exception because you are using Player2, which is null, to get your Player_Controller component.
Player_Controller_taken = Player2.GetComponent<Player_Controller>();
Since you've made Player2 public, it becomes visible within the Unity inspector. Just make sure you're connecting that game object reference in the Unity inspector by dragging and dropping your cube object (which contains your Player_Controller script) from the hierarchy, onto the Player 2 property in the FloatingTextSimple script which is attached to your New Text object.
Do that and you're golden.
...optionally, you could add this to the top of your FloatingTextSimple script's start function.
if (Player2 == null)
{
Player2 = GameObject.Find("Player2");
}
I assume this is what you mean.
This sounds like the easiest solution.
Thank you for responding! And helping!
I have not dragged the object yet because of the following:
I still don't understand how
Player_Controller_taken = Player2.GetComponent<Player_Controller>();
makes my player a null and also "makes" it public.
do you mean that as soon as you call for another object it automatically turns public? and it needs to be assigned?
How would i do this script wise. Cause the solutions seems to be a external fix. if i drag in the inspector. it overwrites it after the code right? is it not better to have it hard coded correctly?
Am still trying to wrap my head around how things work :)
Ok i could not resist to drag it in there XD And it did actually work!
But it just sounds too simple to be true! :P
Is it not better to fix this in the code itself?
I still don't understand how
Player_Controller_taken = Player2.GetComponent();
makes my player a null and also "makes" it public.
Player2 is a public variable because you declared it as such (line 6 of FloatingTextSimple.cs). This exposes it within the Unity Inspector. The game object will be null until you assign it a valid game object. This can be done in code, or the Inspector.
do you mean that as soon as you call for another object it automatically turns public? and it needs to be assigned?
I'm assu$$anonymous$$g this question is regarding the Player2.GetComponent(); call? The GetComponent() method will search the game object that invokes it for the passed in type (Player_Controller, in this case), and return the component if found. If not found, it will return null. Since Player2 was null, GetComponent() couldn't find any components and returned null.
How would i do this script wise. Cause the solutions seems to be a external fix. if i drag in the inspector. it overwrites it after the code right? is it not better to have it hard coded correctly?
Assigning references within the Inspector is a fantastic way to have valid handles to your game objects at load time, rather than searching for that game object in code and assigning at run time. There are many other benefits to this that you can read about here. I personally stay away from the .Find call and very rarely use it. But if assigning your game object references in code is your desire, you can read how to properly use GameObject.Find() here. Hope this helped.
Your answer
![](https://koobas.hobune.stream/wayback/20220613135441im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to change the walk speed of the FPSController from another script? 2 Answers
Position inside or outside of custom shape (select object if inside custom drawn selection) 0 Answers
Get variable from other GameObject's script 3 Answers
determine nearest y outside of mesh from point.y inside 1 Answer
How to get a value and keep it updated 2 Answers