c # - Unity - Error: Object reference not set to an instance of an object

3

I'm a beginner in C # programming, and I'm trying to learn how to make a sidescroller 2d game, but I could not get past a part of the tutorial. This is because the camera simply does not follow the character when I press play and Unity shows an error.

I'm following this video, and although I write in the same way as the guy in the video, Unity gives this error (it happens every frame of the game when I test, so over 11000 errors) :

Video: Click Here .

The error that the console accused was:

Iwanttomakethecamerafollowthecharacterofthegame:

ScriptcodeinC#linkedtothecameratofollowthecharacter(CameraFollow):

usingUnityEngine;usingSystem.Collections;publicclassCameraFollow:MonoBehaviour{privateVector2velocity;publicfloatsmoothTimeY;publicfloatsmoothTimeX;publicGameObjectplayer;voidStart(){player=GameObject.FindGameObjectWithTag("Player");

    }

    void FixedUpdate()
    {
        //O problema diz ser na linha abaixo desse comentário. Eu tentei inverter o posX com o posY, e o erro deu na linha do posY. Também tentei apertar enter e "cortar em vários pedaços" o que está dentro do float posX, o erro parece ser na própria variável posX/posY.
        float posX = Mathf.SmoothDamp(transform.position.x, player.transform.position.x, ref velocity.x, smoothTimeX);
        float posY = Mathf.SmoothDamp(transform.position.y, player.transform.position.y, ref velocity.y, smoothTimeY);

        transform.position = new Vector3(posX, posY, transform.position.z);

    }
}

I already deleted the script and created another with the same code;

I checked all the things that are in the "Hierarchy" tab of the game, none of them have this same Script linked.

    
asked by anonymous 29.05.2016 / 06:49

1 answer

5

In order to resolve this issue you will need to verify that Hierarchy , in the GameObject Player you have the Player tag. As in this image:

SinceinthislineofcodeIdefendthatIwouldhavetohavethistagfortheresttohappen:

player=GameObject.FindGameObjectWithTag("Player"); 
  

Tip: Whenever you want to do something secure without a script having to find a GameObject with a Tag, I advise you to   variable of type public GameObject where when you add Script   as a component, drag from the Hierarchy the GameObject that you want.   So you will not need to find it since it defined who this was.   GameObject.

If you need more information about Tags , I recommend these links from Unity Documentation :

30.05.2016 / 11:21