我收到错误名称mainCamera' does not exist in the current context for the line
targetPos =(Vector2)mainCamera.main.ScreenToWorldPoint(Input.mousePosition);`。我正在寻找答案,但是找不到阻止它的方法。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
float speed = 2f;
Vector2 targetPos;
private Rigidbody2D myRigidbody;
private Animator myAnim;
private static bool playerExists;
public GameObject cameraPrefab;
private void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
if(!playerExists){
playerExists = true;
DontDestroyOnLoad(transform.gameObject);
} else {
Destroy(gameObject);
}
targetPos = transform.position;
GameObject mainCamera = (GameObject)Instantiate(cameraPrefab);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
targetPos = (Vector2)mainCamera.main.ScreenToWorldPoint(Input.mousePosition);
}
if ((Vector2)transform.position != targetPos)
{
Move();
} else {
myAnim.SetBool("PlayerMoving", false);
}
}
答案 0 :(得分:3)
由于mainCamera
是在Start
中定义的局部变量,因此您会收到该特定错误。您尝试在Update
中引用它超出了范围。您可能打算将其定义为班级中的一个字段,因此可以在班级中的任何地方使用mainCamera
来引用它。为此,您应该改为:
// ...
private Rigidbody2D myRigidbody;
private Animator myAnim;
private static bool playerExists;
public GameObject cameraPrefab;
public GameObject mainCamera; // add this line
private void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myAnim = GetComponent<Animator>();
if(!playerExists){
playerExists = true;
DontDestroyOnLoad(transform.gameObject);
} else {
Destroy(gameObject);
}
targetPos = transform.position;
mainCamera = (GameObject)Instantiate(cameraPrefab); // use mainCamera field
mainCamera.tag = "MainCamera"; // tell Unity that it is your main camera.
}
// ...
但是无论如何,Camera.main
是Camera
类的静态属性,因此无论如何您都应该通过Camera
类访问它。
您应该在Update
中使用它:
targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);