Unity Prefab名称“ mainCamera”在当前上下文中不存在

时间:2018-11-20 23:31:50

标签: c# unity3d

我收到错误名称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);
        }
    }

1 个答案:

答案 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.mainCamera类的静态属性,因此无论如何您都应该通过Camera类访问它。

您应该在Update中使用它:

targetPos = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);