大约3小时前,我刚刚开始通过YouTube上的Brackeys开设的“如何制作2D游戏”课程开始学习Unity 2D。我在Ubuntu 18.04上使用Unity 2018.4.1f1,因为我的版本不支持JS,所以我必须改用C#。但是我在第三个视频上遇到了这个错误:GameSetup的变量mainCam尚未分配。这是我在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()
)< / p>
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#