首页 > 解决方案 > 我想在 Unity 中从一个脚本访问另一个脚本的公共方法。我试过下面的代码

问题描述

从公共访问ObjectPoolingManager.Instance.GetBullet();时出现以下错误Player.csGameObject GetBulltet ()ObjectPoolingManager.cs

Assets\SPF_Assets\Scripts\Game\Player.cs(4,7): error CS0138: A 'using namespace' directive can only be applied to namespaces; 'ObjectPoolingManager' is a type not a namespace. Consider a 'using static' directive instead

Player.cs 脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ObjectPoolingManager; //Tried this, didnt work

public class Player : MonoBehaviour
{
    public Camera playerCamera;
    public GameObject bulletPrefab;
    // Update is called once per frame
    void Update() {
        if(Input.GetMouseButtonDown(0)){
            ObjectPoolingManager.Instance.GetBullet();

            GameObject bulletObject = Instantiate (bulletPrefab);
            bulletObject.transform.position = playerCamera.transform.position + playerCamera.transform.forward;
            bulletObject.transform.forward = playerCamera.transform.forward;
        }
    }
}

对象池管理器.cs

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

public class ObjectPoolingManager : MonoBehaviour {

    private static ObjectPoolingManager instance;
    public static ObjectPoolingManager Instance { get { return instance; } }

    // Start is called before the first frame update
    void Awake () {
        instance = this;
    }

    public GameObject GetBulltet () {
        Debug.Log ("Hell0");
        return null;
    }
}

标签: visual-studiounity3dgame-enginegame-development

解决方案


我多次重新阅读代码,终于意识到你的答案已经在你的问题中了:

I am getting the below error while accessing
ObjectPoolingManager.Instance.GetBullet(); in Player.cs
from public GameObject GetBulltet () which is in ObjectPoolingManager.cs

我在您的代码中验证了这一点,您实际上调用了一个函数ObjectPoolingManager.Instance.GetBullet(),即使没有这样的函数,而是GetBulltet()应该GetBullet()改为。


推荐阅读