Unity Player Holdingball问题

时间:2019-01-30 04:31:34

标签: c# unity3d

我正在统一进行篮球比赛,第一人称的球员能够将球投进篮筐,但我遇到了错误

  

资产/项目/脚本/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);
            }
    }
}
}

1 个答案:

答案 0 :(得分:0)

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