- Home /
My MainCharacter is not being instantiated when awake?
I am a beginner in unity i am learning using recreating a project .When I run project I get an error "Object reference not set to an instance of an object GameManager.Awake () (at Assets/Scripts/GameManager.cs:97)". My MainCharater(project has multiple Characters) is not loading on awake not even in scene/inspector.
Here is Awake() function script
public class GameManager : MonoBehaviour
{
private void Awake()
{
if (Instance == null)
{
Instance = this;
}
else
{
UnityEngine.Object.DestroyImmediate(Instance.gameObject);
Instance = this;
}
CreateNewCharacter(CharacterManager.Instance.CurrentCharacterIndex);
}
I am facing issues in CreateNewCharacter from CurrentcharacterIndex.
public class CharacterManager : MonoBehaviour
{
public static readonly string CURRENT_CHARACTER_KEY = "MY_CURRENT_CHARACTER";
public GameObject[] characters;
public static CharacterManager Instance
{
get;
private set;
}
public int CurrentCharacterIndex
{
get
{
return PlayerPrefs.GetInt(CURRENT_CHARACTER_KEY, 0);
}
set
{
PlayerPrefs.SetInt(CURRENT_CHARACTER_KEY, value);
PlayerPrefs.Save();
}
}
I am not getting it does this have to do with json or something else please help me by elaborating with pics Thankyou..
Answer by SkaredCreations · May 28, 2020 at 11:19 AM
In your GameManager class you are using CharacterManager.Instance assuming that it has been already loaded and set (if line 97 of GameManager is the Awake method, else you need to check what you're doing at that line), it may be that instead it has not been loaded/set yet. You could try to set the scripting order to have CharacterManager before GameManager or you could move the call to CreateNewCharacter(..) inside a coroutine that waits until CharacterManager.Instance has been set:
void Awake()
{
// ....
StartCoroutine(CreateNewCharacterAsync());
}
IEnumerator CreateNewCharacterAsync()
{
while (CharacterManager.Instance == null)
yield return new WaitForEndOfFrame();
CreateNewCharacter(CharacterManager.Instance.CurrentCharacterIndex);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612235405im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity 3.4 Prefab Instance Rotation Issue 0 Answers
Playing an Instintiated particle system prefab. 1 Answer
Instantiate a COMPLETELY Unique Instance of an Object 1 Answer
Instanciate gameobject from Resources subfolder 1 Answer
C# Object reference not set to an instance of an object right after GameObject.Instantiate 1 Answer