Неназначенная переменная в Unity - PullRequest
0 голосов
/ 01 июня 2019

Я только начал изучать Unity 2D с курса «Как сделать 2D-игру» от Brackeys на YouTube около 3 часов назад. Я использую Unity 2018.4.1f1 в Ubuntu 18.04, и потому что JS не поддерживается в моей версии, поэтому я должен использовать C # вместо этого. Но я столкнулся с этой ошибкой в ​​третьем видео: переменная mainCam из GameSetup не была назначена. Это мой код в C #:

GameSetup.cs

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

public class GameSetup : MonoBehaviour
{
    public Camera mainCam;

    public BoxCollider2D topWall, bottomWall, leftWall, rightWall;

    public Transform Player1, Player2;

    // Start is called before the first frame update
    void Start()
    {
        // topWall = GetComponent<BoxCollider2D>();
        // mainCam = GetComponent<Camera>();
        // If I uncomment this, there would be a new error: There is no 'Camera' attached to '_GM' game object, but a script is trying to access it.
    }

    // Update is called once per frame
    void Update()
    {
        // Move each wall to its edge location
        topWall.size = new Vector2(mainCam.ScreenToWorldPoint(new Vector3(Screen.width * 2.0f, 0f)).x, 1.0f);
        topWall.offset = new Vector2(0f, mainCam.ScreenToWorldPoint(new Vector3(0f, Screen.width, 0f)).y + 0.5f);
    }
}

С помощью Google я добавил rb2d.GetComponent<Rigibody2D>() в Start() из сценария второго видео ниже и предотвратил ошибку (в видео нет Start())

PlayerControls.cs


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


public class PlayerControls : MonoBehaviour
{

    public KeyCode moveUp, moveDown;

    public float speed = 10;

    private Rigidbody2D rb2d = new Rigidbody2D();
    // Start is called before the first frame update
    void Start()
    {
        rb2d = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(moveUp))
        {
            Vector3 v = rb2d.velocity;
            v.y = speed;
            rb2d.velocity = v;
            // rb2d.velocity.y = speed;
        }
        else if (Input.GetKey(moveDown))
        {
            Vector3 v = rb2d.velocity;
            v.y = speed * (-1);
            rb2d.velocity = v;
        }
        else
        {
            Vector3 v = rb2d.velocity;
            v.y = 0;
            rb2d.velocity = v;
        }
    }
}

Как я могу исправить ошибку в GameSetup.cs? Я сделал именно то, что сказано в видео, но только изменил язык с JS на C #

1 Ответ

1 голос
/ 01 июня 2019

Либо присвойте ему значение null:

public Camera mainCam = null;

Но вам, скорее всего, не хватает прикрепить объект камеры к нему в редакторе Unity3D.Проверьте инспектора и убедитесь, что объект, использующий этот сценарий (GameSetup.cs), имеет объект камеры, назначенный его общедоступной переменной.

GameObject with public variables in the form of GameObjects Должно выглядеть примерно так.Вы должны перетащить объект камеры в Gameobject.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...