Null Reference when trying to set something to a variable in another script

I am having problem to set something to a variable that is in another script, but in the same gameobject. Here is the part of my code that is giving me trouble

constructions[1] = (GameObject)PhotonNetwork.Instantiate ("Foundation", new Vector3 (transform.position.x + 3, transform.position.y, transform.position.z + 3), transform.rotation,0 );
gameObject.GetComponent<CharacterControllerMultiplayer> ().grabbedObject = constructions [1];

The object is being Instantiate just fine, but i can’t set it to the variable that is in another script.

The var grabbedObject is like this: public GameObject grabbedObject;

Even if i create something like an int in CharacterControllerMultiplayer and try to set it through the other script i get the error, which is btw: NullReferenceException : Object reference not set to an instance of an object.

Can someone tell me what am i doing wrong. I think that i am doing the wrong aproaching in the access things from another scripts.

Thank you!

Try to add this.gameObject in line two at the start. It may not recognize what gameObject you are referencing to.

1 Answer

1

GetComponent will return null if there isn’t actually a component of that type on the same game object. I know you think it’s there, but the symptoms indicate that it’s not, so please double-check. Perhaps this script is on a sub-object of the one with the CharacterControllerMultiplayer on it, or perhaps you have a CharacterController instead of a CharacterControllerMultiplayer, or something else.

Anyway, look at all the components on a single game object, and if you don’t find both the script containing the above code, and the CharacterControllerMultiplayer, then there’s your problem!

Yeah, that is definitely the problem. I changed the way that i was accessing the function and now it is working. Thank you a lot!