existing GameObject gives nullreference when trying to acces Instantiated gameojbect

Hi when hero changes scene ım Instantiating it to another scene and camera follows it via code but ım using
findobjectwithtag to find hero and it gives nullreference why its giving nullreferenceexception

this is herocreator script

 public void herocreate()
    {
        if (main_hero_move.herocreate == 3&& herocreator)
        {

            Instantiate(heroo, getpos, Quaternion.identity);
            herocreator = false;

        }


    }

this is camera script it gives nullreference on line 28 29 dx dy fields.

public GameObject player;
    float dx ,dy;
    float x, y,z;
    Rigidbody2D rb;


    private void Awake()
    {
        player = GameObject.FindGameObjectWithTag("Main_hero");
    }
    void Start()
    {
        z = -100;
        rb = GetComponent<Rigidbody2D>();
 
    }

    // Update is called once per frame
    void Update()
    {
      //  if (player != null)
        {
            float a, b;
            dy = player.transform.position.y - transform.position.y;
            dx = player.transform.position.x - transform.position.x;

it works if ı add
player = GameObject.FindGameObjectWithTag(“Main_hero”);
if (player != null){
}
to update function

It’s set to null because, quite simply, it can’t find the character when Awake() is called on the camera. When do you create the new camera? If possible, feed the new character to the camera instead of relying on the camera having to find the character.

1 Like

It is null because it can’t be found when you are checking for it. It is not really clear from your explanation when you are instantiating the hero object in relation to the camera, but if the camera is a part of the scene and the hero object is being instantiated, the hero likely won’t exist yet when the camera’s awake is called.

1 Like

you are right but is there any way to fix it creating camera probably will work but ı think there is better solution

make sure your prefab is instantiated before you use findwithtag method.

@GroZZleR had a good suggestion of having the instantiated hero object find the camera and set up the reference, instead of the other way around.

For feeding important stuff from one object to another that it creates, I like this pattern:

Factory Pattern in lieu of AddComponent (for timing and dependency correctness):

https://gist.github.com/kurtdekker/5dbd1d30890c3905adddf4e7ba2b8580