[Closed]NullReferenceException on Object Instantiation onto game world

Here’s my code

var playerMale : GameObject;
var playerFemale : GameObject;

var savedplayer : int = 0;

function Awake () {
	savedplayer = PlayerPrefs.GetInt("selectedplayer");
	
	playerMale = GameObject.Find("Cube1_M");
	playerFemale = GameObject.Find("testchar_F");
	
	if(savedplayer == 0){
	}
	else if(savedplayer == 1){
		playerMale.SetActiveRecursively(true);
		playerFemale.SetActiveRecursively(false);
	
	}
	else if(savedplayer == 2){
		playerMale.SetActiveRecursively(false);
		playerFemale.SetActiveRecursively(true);
	}
}

function Update () {

}

I put that code on the Main Camera on Game Scene.

and this code goes to an object to choose Character (Male of Female) on CharSelection Scene.

var isMale = false;
var isFemale = false;
var selectedplayer : int = 0;

function OnMouseUp() {

	if(isMale == true) {
		PlayerAttributes.player_gender="Male";
		print(PlayerAttributes.player_gender);
		GameObject.Find("Cube1_M").transform.position.x = -1.7;
		GameObject.Find("testchar_F").transform.position.x = -5;
		selectedplayer = 1;
		PlayerPrefs.SetInt("selectedplayer", (selectedplayer));
	}
	if(isFemale == true) {
		PlayerAttributes.player_gender="Female";
		print(PlayerAttributes.player_gender);
		GameObject.Find("Cube1_M").transform.position.x = -5;
		GameObject.Find("testchar_F").transform.position.x = -1.7;
		selectedplayer = 2;
		PlayerPrefs.SetInt("selectedplayer", (selectedplayer));
	}

}

but when i press button to load the Game Scene, the object did not appear at the scene, and the error is NullReferenceException on ActiveRecursively function…

could anybody help me out?

GameObject.Find is something you should not use unless you have no other option. Instead, expose playerMale and playerFemale in the inspector, then drag and drop the objects from the scene.

You just need to create a new script with :

function Awake () {
	DontDestroyOnLoad (transform.gameObject);
}

In it, and attach it to the “Character” game object, because it contains the two game objects you need. Or you can attach the script directly to Cube1_M and testchar_F, this should work too !