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

Asked

Viewed 1,124 times

3

I’m a beginner in C#programming, and I’m trying to learn how to make a 2d sidescroller game, but I couldn’t move forward from a part of the tutorial. This is because the camera simply doesn’t follow the character when I press play and Unity shows an error.

I’m following this video (in English), and although I write the same way as the guy in the video, Unity gives this error (happens to each frame of the game when I test, so more than 11000 errors):

Video: Click Here.

The Error the console accused was:

I want to make the camera follow the character of the game:

Script code in c# linked to the camera to follow the character (Camerafollow):

using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour
{

    private Vector2 velocity;

    public float smoothTimeY;
    public float smoothTimeX;

    public GameObject player;

    void Start()
    {

        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 the same Script linked.

  • Gameobject Player is tagged "Player"?

  • Yeah, if tag means his name, he’s

  • No, the tag is that

  • He was not, I put as Player and now the camera follows, thanks, I can’t believe I was stuck so long to have such a simple solution kkkk

  • @Kylbert did not notice that they had already helped him in the comments, I will always write in reply the solution of the questions, even if it finds solution, then answer his own questions, since then it will be able to help other people, in this case it will no longer be necessary, since I already answered and added some relevant information. Now just accept my answer and this question will be resolved. I hope I helped both in Unity and in the advice on SOPT. Greetings!

  • Yes, thanks for the advice and information. As you might see I’m new here so I didn’t know much about running. Your reply was accepted and marked as useful :)

Show 1 more comment

2 answers

5


In order to resolve this issue you will have to check whether Hierarchy, in Gameobject Player is tagged Player. Just like in this picture:

Tag Player

Since in this line of code I would have to have that tag, for the rest to happen:

player = GameObject.FindGameObjectWithTag("Player"); 

Suggestion: whenever you want to do something safe without a Script having to find a Gameobject with a Tag, I advise you to target a type public GameObject where when to add Script as a component, drag the Gameobject you want from the Hierarchy. So you won’t need to find him since you defined who that was Gameobject.

If you need more information about Tags, I advise you these links from Unity documentation:

-1

using UnityEngine;
using System.Collections;

/*Código do script em c# vinculado à câmera para seguir o personagem (CameraFollow):/*


public class CameraFollow : MonoBehaviour 
{
    public float xMargin = 1f;      // Distância no eixo x que o jogador pode mover antes da câmera seguir.
    public float yMargin = 1f;      // Distância no eixo y, o jogador pode mover-se antes da câmera seguir.
    public float xSmooth = 8f;      // Quão suave a câmera alcança seu movimento alvo no eixo x.
    public float ySmooth = 8f;      // Quão suavemente a câmera alcança com o movimento do alvo no eixo y.
    public Vector2 maxXAndY;        // As coordenadas máximas x e y que a câmera pode ter.
    public Vector2 minXAndY;        // As coordenadas mínimas x e y que a câmera pode ter.

    private Transform player;       // Referência à transformação do jogador.


    void Awake ()
    {
        // Configurando a referência.
        player = GameObject.FindGameObjectWithTag("Player").transform;
    }


    bool CheckXMargin()
    {
        // Retorna verdadeiro se a distância entre a câmera eo jogador no eixo x for maior que a margem x.
        return Mathf.Abs(transform.position.x - player.position.x) > xMargin;
    }


    bool CheckYMargin()
    {
        // Retorna verdadeiro se a distância entre a câmera e o jogador no eixo y for maior que a margem y.
        return Mathf.Abs(transform.position.y - player.position.y) > yMargin;
    }


    void FixedUpdate ()
    {
        TrackPlayer();
    }
    
    
    void TrackPlayer ()
    {
        // Por padrão, as coordenadas x e y do alvo da câmera são as coordenadas x e y atuais.
        float targetX = transform.position.x;
        float targetY = transform.position.y;

        // Se o jogador se moveu para além da margem x ...
        if (CheckXMargin())
            // ... a coordenada x do alvo deve ser um Lerp entre a posição x atual da câmera e a posição x atual do jogador.
            targetX = Mathf.Lerp(transform.position.x, player.position.x, xSmooth * Time.deltaTime);

        // Se o jogador se moveu para além da margem Y ...
        if (CheckYMargin())
            // ... a coordenada y do alvo deve ser um Lerp entre a posição atual da câmera e a posição atual do jogador.
            targetY = Mathf.Lerp(transform.position.y, player.position.y, ySmooth * Time.deltaTime);

        // As coordenadas x e y do alvo não devem ser maiores que o máximo ou menor do que o mínimo.
        targetX = Mathf.Clamp(targetX, minXAndY.x, maxXAndY.x);
        targetY = Mathf.Clamp(targetY, minXAndY.y, maxXAndY.y);

        // Defina a posição da câmera para a posição de destino com o mesmo componente z.
        transform.position = new Vector3(targetX, targetY, transform.position.z);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.