- Home /
Cannot access sprite of a gameobject
I am making a character selection script (similar to super smash brothers).
When the player presses Start on the controller, I instantiate a "Player1" object. When they pick a character, I would like the Player1 object to render that character's sprite. I saw a lot of other people have asked and had this question solved, but I think I'm making a silly mistake somewhere.
var p1;
function Update(){
if ( Input.GetButtonDown("Start_1") && GlobalHandlerScript.player1Joined == false ){
//set the "player1Joined" variable
GlobalHandlerScript.joined("Player1");
//instantiate player
p1 = Instantiate(GlobalHandlerScript.player1);
}
if ( Input.GetButtonDown("A_1") && GlobalHandlerScript.player1Joined == true ){
//find the object they selected, make it their sprite
Debug.Log("searching for object");
var selected = GameObject.Find("Fire Wizard");
Debug.Log("found object, searching for sprite");
var p1sprite = selected.GetComponent(SpriteRenderer).sprite;
Debug.Log("found sprite, assigning sprite");
p1.GetComponent(SpriteRenderer).sprite = p1sprite; /*BREAKS HERE*/
Debug.Log("assigned sprite");
}
}
It breaks with a NullReferenceException: Object reference not set to instance of an object.
It breaks directly after saying "searching for sprite" but before saying "found sprite", meaning it's breaking at the assignment of p1sprite. Could someone explain exactly what's causing the Null Reference Exception?
Answer by Kiwasi · Aug 28, 2014 at 03:58 AM
Do the GameObject found and P1 both have a SpriteRenderer?
That's the most obvious null reference here.
Next step is to Debug.Log everything involved in the problem line to find out which is null.
Debug.Log(selected);
Debug.Log(selected.GetComponent(SpriteRenderer));
Debug.Log(p1);
Debug.Log(p1.GetComponent(SpriteRenderer));
One of these will print null to the console, identifying your error.
p1 is null, but it was instantiated properly in the game, AND affected by other code using the same reference.
p1 = Instantiate(GlobalHandlerScript.player1);
p1.transform.position.x = -7;
p1.transform.position.y = -3.5;
p1.transform.localScale.x = .3;
p1.transform.localScale.y = .3;
All of this code happened properly earlier in the same script. Did it somehow get cleared?
I think I got it, it had to I misunderstood how instantiate worked, and ended up clearing p1 using another function. I didn't post it because I thought it was entirely unrelated, but thanks to those simple println statements that I really should have thought to do on my own, I followed the trail and found the problem. Thanks for the suggestion :P