【问题标题】:I want to access a public method from one script to another in Unity. I have tried the below code我想在 Unity 中从一个脚本访问另一个脚本的公共方法。我试过下面的代码
【发布时间】:2020-09-19 08:33:14
【问题描述】:

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

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;
        }
    }
}

ObjectPoolingManager.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;
    }
}

【问题讨论】:

  • 删除此行using ObjectPoolingManager; //Tried this, didnt work
  • 也试过了,还是不行。评论说。
  • 如果该行真的被删除了,至少应该修改错误信息,因为Player.cs的第4行现在是空的。
  • 我删除了那一行,现在是这个:Assets\SPF_Assets\Scripts\Game\Player.cs(12,43): error CS1061: 'ObjectPoolingManager' does not contain a definition for 'GetBullet' and没有可访问的扩展方法“GetBullet”接受“ObjectPoolingManager”类型的第一个参数
  • 我认为这是一个错字,因为方法名称是GetBulltet

标签: visual-studio unity3d game-engine game-development


【解决方案1】:

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

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()

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 2021-10-11
    • 2022-11-01
    相关资源
    最近更新 更多