【问题标题】:Unity Player Holdingball IssueUnity Player 持球问题
【发布时间】:2019-01-30 04:31:33
【问题描述】:

我正在统一制作篮球游戏,第一人称的球员能够将球射入篮筐,但我遇到了错误

Assets/Project/Scripts/GameController.cs(19,14):错误 CS0122: `Player.holdingBall' 由于其保护级别而无法访问

如何解决此类错误?

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

public class GameController : MonoBehaviour {
    public Player player;
    public float resetTimer = 5f;



    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (player.holdingBall == false) {
            resetTimer -= Time.deltaTime;
            if (resetTimer <= 0) {
             SceneManager.LoadScene("Game");
            }
        }

    }
}

这是我的播放器脚本

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

public class Player : MonoBehaviour {

    public GameObject ball;
    public GameObject playerCamera;

    public float ballDistance = 2f;
    public float ballThrowingForce = 5f;

    private bool holdingBall = true;

    // Use this for initialization
    void Start () {
        ball.GetComponent<Rigidbody> ().useGravity = false;
    }

    // Update is called once per frame
    void Update () {
        if (holdingBall) {
      ball.transform.position = playerCamera.transform.position + playerCamera.transform.forward * ballDistance;
            if (Input.GetMouseButtonDown(0)) {
                holdingBall = false;
                ball.GetComponent<Rigidbody>().useGravity = true;
                ball.GetComponent<Rigidbody>().AddForce(playerCamera.transform.forward * ballThrowingForce);
            }
    }
}
}

【问题讨论】:

标签: c# unity3d


【解决方案1】:
private bool holdingBall = true;

private,因此无法使用

player.holdingBall

要么将其设为public 字段,如

public bool holdingBall = true;

此解决方案的缺点是您还可以在其他地方设置该值。

所以最好为它创建一个只读的public 属性

private bool holdingBall = true;

public bool HoldingBall
{
    get { return holdingBall; }
}

所以只能读取,不能设置使用

if(!player.HoldingBall) 
{
    ...
}

您也可以完全跳过私有字段并仅使用类似的属性

public bool HoldingBall{ get; private set; }

【讨论】:

  • 我把 public bool HoldingBall { get { return holdingBall; } } 在我的播放器脚本的顶部或底部,但它不起作用。我究竟应该在我的脚本中的哪个位置放置这个属性?
  • “不起作用”到底是什么意思?把它放在Player 类的某个地方
  • 我有这样的课程 codepublic class Player : MonoBehaviour { public bool HoldingBall { get { return holdingBall; } } 公共 GameObject 球;公共游戏对象 playerCamera;公众浮球距离 = 2f; public float ballThrowingForce = 5f;code 我得到 2 个统一错误。我把它放在正确的地方了吗?
  • 如果将HoldingBallreturn holdingBall 一起使用,您仍然需要private bool holdingBall
  • 我把这些放在我的玩家类的顶部 private bool holdingBall = true;公共布尔控股球{得到{返回控股球; } } 我仍然得到了 player.holdingball 无法访问的保护。
猜你喜欢
  • 1970-01-01
  • 2020-05-18
  • 2017-07-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
  • 2015-09-09
  • 2016-08-20
  • 2022-11-23
相关资源
最近更新 更多