- Home /
Error Assigning GameObject To Var Inside A Class
when i try to assign a variable inside a class, using the following code:
static var Player : PlayerVariables;
class PlayerVariables
{
var PlayerObj : GameObject;
}
Start()
{
Player.PlayerObj = GameObject.Find("Player"); // there is a object in the scene called Player
}
i get a NullReferenceException: Object reference not set to an instance of an object
Didn't you just ask this one? For starters, don't spell variables with Upper Case letters. Are you sure that there is an object with the name "Player" in your scene? That seems to be the only problem with that exact line.
Answer by Flynn · Oct 16, 2011 at 04:56 AM
Okay... Player.PlayerObj = GameObject.Find("Player");
Since GameObject.Find() will not return an error if no object was found, this is not causing the error. Since assigning any variable, even a null one, to null will not cause an error, .PlayerObj is not causing the error. The only thing that could be going wrong is trying to do Player.PlayerObj. In other words, the variable Player is null! To double check this, insert Debug.Log("Player is null? " + ((Player == null)?"YES" : "NO")); directly before "Player.PlayerObj =...". Check your debug console for the result.
EDIT: I must have misread your code or something lol. Of COURSE Player is null, you never initialize it.
player = new PlayerVariables(); needs to be put in your Start function :) (Thanks, syclamoth!)
I would have thought you would have to assign a new PlayerVariables object at the start, as in
static var Player : PlayerVariables = new PlayerVariables();
But I'm honestly not sure how constructors work in javascript.
Answer by mcwind · Oct 16, 2011 at 05:26 AM
I'm not Familiar with js but mabye you can code like this:
static var Player : PlayerVariables = new PlayerVariables(); class PlayerVariables { var PlayerObj : GameObject; }
Start() { Player.PlayerObj = GameObject.Find("Player"); // there must be an object in the scene called Player }
Answer by huttch · Oct 16, 2011 at 05:38 AM
its the static thats causing the problem for some reason
Your answer
Follow this Question
Related Questions
simple coding problem 1 Answer
cannot be assigned to (it is read-only) Problem 2 Answers
Displaying a static variable from another script with OnGUI 1 Answer
Using a static class & pass in gameObject or just add same script to multiple objects 1 Answer
An object reference is required to acess non-static member. 1 Answer