代码之家  ›  专栏  ›  技术社区  ›  Keith Power

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

  •  1
  • Keith Power  · 技术社区  · 5 年前

    我得到错误的名字 mainCamera' does not exist in the current context for the line targetpos=(vector2)maincamera.main.screentownorldpoint(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 回复  |  直到 5 年前
        1
  •  3
  •   Ruzihm aks786    5 年前

    你得到了那个特别的错误,因为 mainCamera 是在中定义的局部变量 Start . 它超出了您试图引用它的范围 Update . 您可能打算将它定义为类中的一个字段,因此可以使用 主摄像机 在你班的任何地方。要做到这一点,您应该改为:

    // ...
    
    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 类,因此您应该通过 照相机 不管怎样上课。

    你应该把这个用在 更新 而是:

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