A
A
Azamat742018-12-30 12:23:44
C++ / C#
Azamat74, 2018-12-30 12:23:44

Error in unity (c#), what to do?

Good afternoon.
I ran into a problem that I can’t solve in any way.
In unity, I create a 2d game (tds) and when compiling this code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float offset = 0.0f;
    public float speed = 0.5f;

    private void Update()
    {
        Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; // указывает на эту строку
        difference.Normalize();
        float rotation_z = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0f, 0f, rotation_z + offset);

        float moveUp = Input.GetAxis("Vertical");
        float moveLeft = Input.GetAxis("Horizontal");
        GetComponent<Rigidbody2D>().velocity = new Vector2(moveLeft, moveUp) * speed;
    }
}

Throws NullReferenceException: Object reference not set to an instance of an object
A bit about the code: in general, I get the cursor coordinates and rotate the character in this direction, but the control keys should remain constant
Help!!!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
GavriKos, 2018-12-30
@GavriKos

1) NalRef - execution error, not compilation
2) The error itself must contain a line. Which?
3) GetComponent in Update is a terrible evil. By the way, most likely there is an error in this line - is there Rigidbody2d on the object?

P
p4p, 2018-12-30
@p4p

GetComponent only in Start as GavriKos already noted .
NullReferenceException: Object reference not set to an instance of an object - something can be found.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question