error CS0122: inaccessible due to its protection level

Hello!

At that moment i came to new company, where i should modify existing code, but i have some troubles
I have 2 existing scripts, and 3-rd is mine

I’m getting this error at my script: Assets/ProjectFiles/scripts/BTNEnterViewFloorState.cs(13,62): error CS0122: `CameraTargetScript.viewStateChanged(AppController.CR_VIEW_STATE)’ is inaccessible due to its protection level

1-st script AppController

public class AppController : MonoBehaviour {

    public enum CR_VIEW_STATE
    {
        VIEW_NONE =                        0,
        VIEW_BUILDING =                    1,
        VIEW_FLOOR =                    2,
        VIEW_APARTMENT =                3,
        VIEW_PANORAMA =                    4,
    };
}

2nd script CameraTargetScript

public class CameraTargetScript : MonoBehaviour {
    //public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
    //public RotationAxes axes = RotationAxes.MouseXAndY;
    public float sensitivityX = 14F;
    public float sensitivityY = 14F;
    public float minimumX = -360F;
    public float maximumX = 360F;
    public float minimumY = -90F;
    public float maximumY = 0F;
    public float rotationX = 0F;
    public float rotationY = 0F;

    bool mouseLeftButtonDown = false;
    bool mouseMiddleButtonDown = false;

    private Quaternion originalRotation;
    private Camera m_camera;
    private Transform cameraTransform, _transform;

    // Zooming vars
    public float perspectiveZoomSpeed = 1F;
    public float minimumZoomDistance = 1F;
    public float maximumZoomDistance = 300F;
    private float mouseAxisFactor = 15F;

    // Moving vars
    public float MoveSpeed = 5F;

    // Debug only variables
    /*Sanat - 20151013: неиспользуется нигде
    string txt = null;
    */
    public Quaternion lastEndPos;

    class CameraPosition {
        public CameraPosition() {}
        public CameraPosition(Vector3 pos, float dist) {
            position = pos;
            distance = dist;
        }
        public Vector3 position;
        public Quaternion rotation;
        public float distance;
    }

    // m_camera transformation vars
    Stack<CameraPosition> positionStack = new Stack<CameraPosition>();
    public float transfomTime = 1f;
    float transfomTimeLeft = 0f;
    CameraPosition newPos;
    CameraPosition oldPos;

    //Sanat - 20151014
    public void OnEnable() {
        AppController.OnControlModeChanged += controlModeChanged;
        AppController.OnViewStateChanged += viewStateChanged;
    }

    public void OnDisable() {
        AppController.OnControlModeChanged -= controlModeChanged;
        AppController.OnViewStateChanged -= viewStateChanged;
    }

    void Start ()
    {
        _transform = transform;
        m_camera = GetComponentInChildren<Camera>();
        if (m_camera == null) {
            Debug.LogError("Can't find any m_camera!!!");
        }
        cameraTransform = m_camera.transform;
   
        // Initialize m_camera position
        cameraTransform.position = _transform.position;
        cameraTransform.rotation = _transform.rotation;
        cameraTransform.Translate(Vector3.forward * maximumZoomDistance);
        cameraTransform.LookAt (_transform.position);
   
        originalRotation = _transform.localRotation;
        lastEndPos = _transform.localRotation;
   
        positionStack.Push(getCurrentPosition());
    }

    CameraPosition getCurrentPosition ()
    {
        CameraPosition pos = new CameraPosition();
        pos.position = _transform.localPosition;
        pos.rotation = _transform.localRotation;
        pos.distance = m_camera.transform.localPosition.z;
        return pos;
    }

    void Update ()
    {
        if (m_camera.enabled) {
            // =============================================
            // Zooming
            // =============================================
            if (Input.touchCount  == 2)
            {
                Touch touchZero = Input.GetTouch (0);
                Touch touchOne = Input.GetTouch (1);
           
                Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
                Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
           
                float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
                float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
           
                float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
           
                float distance = m_camera.transform.position.magnitude - transform.position.magnitude;
           
                if (((deltaMagnitudeDiff < 0) && (distance > minimumZoomDistance )) ||
                    ((deltaMagnitudeDiff > 0) && (distance < maximumZoomDistance)))
                    #if UNITY_IOS
                    m_camera.transform.Translate(Vector3.forward * -deltaMagnitudeDiff * perspectiveZoomSpeed * 0.1);
                #else
                m_camera.transform.Translate(Vector3.forward * -deltaMagnitudeDiff * perspectiveZoomSpeed);
                #endif
           
                //m_camera.fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;
           
                //m_camera.fieldOfView = Mathf.Clamp (m_camera.fieldOfView, minimumZoomDistance, maximumZoomDistance);
            }
            // Mouse zoom support
            if (Input.GetAxis ("Mouse ScrollWheel") != 0) {
                float distance = m_camera.transform.position.magnitude - transform.position.magnitude;
                Debug.Log("Dist:" + distance);
                if (((distance > minimumZoomDistance) &&  (Input.GetAxis ("Mouse ScrollWheel") > 0)) ||
                    ((distance < maximumZoomDistance) &&  (Input.GetAxis ("Mouse ScrollWheel") < 0)))
                    m_camera.transform.Translate(Vector3.forward * Input.GetAxis ("Mouse ScrollWheel") * mouseAxisFactor * perspectiveZoomSpeed);
                //m_camera.fieldOfView += -Input.GetAxis ("Mouse ScrollWheel") * mouseAxisFactor * perspectiveZoomSpeed;       
                //m_camera.fieldOfView = Mathf.Clamp (m_camera.fieldOfView, minimumZoomDistance, maximumZoomDistance);
                //txt = "fieldOfView: " + m_camera.fieldOfView;
            }
            // =============================================
       
            // =============================================
            // Rotating m_camera around the target
            // =============================================
       
            if(Input.GetMouseButtonDown(0)) {
                mouseLeftButtonDown = true;
            }
            if(Input.GetMouseButtonUp(0)) {
                mouseLeftButtonDown = false;
            }
            if(Input.GetMouseButtonDown(2)) {
                mouseMiddleButtonDown = true;
            }
            if(Input.GetMouseButtonUp(2)) {
                mouseMiddleButtonDown = false;
            }
            if (mouseLeftButtonDown) {
                // Read the mouse input axis
                if ((Input.touchCount > 0)) {
                    if ((Input.touchCount == 1) && Input.GetTouch(0).phase == TouchPhase.Moved){
                        #if UNITY_IOS
                        rotationX += Input.touches[0].deltaPosition.x * sensitivityX * 0.1;
                        rotationY += Input.touches[0].deltaPosition.y * sensitivityX * 0.1;
                        #else
                        rotationX += Input.touches[0].deltaPosition.x * sensitivityX;
                        rotationY += Input.touches[0].deltaPosition.y * sensitivityX;
                        #endif
                    }
                } else {
                    rotationX += Input.GetAxis("Mouse X") * sensitivityX;
                    rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
                }
           
                //Debug.Log("Position: Y:" + rotationY + " X:" + rotationX);
           
                rotationX = ClampAngle (rotationX, minimumX, maximumX);
                rotationY = ClampAngle (rotationY, minimumY, maximumY);
           
                Quaternion xQuaternion = Quaternion.AngleAxis (rotationX, Vector3.up);
                Quaternion yQuaternion = Quaternion.AngleAxis (rotationY, Vector3.right);
           
                lastEndPos = xQuaternion * yQuaternion;
           
                //transform.localRotation = originalRotation * xQuaternion * yQuaternion;
                transform.rotation = Quaternion.Slerp(transform.rotation, originalRotation * lastEndPos, 5f * Time.deltaTime);
            } else {
                //Плавно поворачиваем камеру с исходного положения в положение lastEndPos
                transform.rotation = Quaternion.Slerp(transform.rotation, originalRotation * lastEndPos, 5f * Time.deltaTime);
            }
            //Debug.Log("5f * Time.deltaTime:"  + 5f * Time.deltaTime);
       
            if (mouseMiddleButtonDown) {
                float Xdelta = Input.GetAxis("Mouse X");
                float Ydelta = Input.GetAxis("Mouse Y");
                transform.Translate(Vector3.up * -Ydelta);
                transform.Translate(Vector3.right * Xdelta);
            }
            // =============================================
       
       
            if (Input.touchCount  == 2)
            {
                if ((Input.GetTouch (0).phase == TouchPhase.Moved ) && (Input.GetTouch (1).phase == TouchPhase.Moved)){
                    // Store both touches.
                    Touch touchZero = Input.GetTouch (0);
                    Touch touchOne = Input.GetTouch (1);
               
                    // Taking coords to set direction of inputs
                    float horizontalZero = touchZero.deltaPosition.x ;
                    float verticalZero   = touchZero.deltaPosition.y;
               
                    float horizontalOne = touchOne.deltaPosition.x;
                    float verticalOne   = touchOne.deltaPosition.y;
                    #if UNITY_IOS
                    int k = 0.1;
                    #else
                    int k = 1;
                    #endif
                    if ((horizontalZero > 0) && (horizontalOne > 0)) {
                        transform.Translate(Vector3.right * MoveSpeed * Time.deltaTime * k);
                    }
                    if ((horizontalZero < 0) && (horizontalOne < 0)) {
                        transform.Translate(Vector3.left * MoveSpeed * Time.deltaTime * k);
                    }
                    if ((verticalZero > 0) && (verticalOne > 0)) {
                        transform.Translate(Vector3.down * MoveSpeed * Time.deltaTime * k);
                    }
                    if ((verticalZero < 0) && (verticalOne < 0)) {
                        transform.Translate(Vector3.up * MoveSpeed * Time.deltaTime * k);
                    }
                }
            }
        }
    }

    public static float ClampAngle (float angle, float min, float max)
    {
        if (angle < -360F)
            angle += 360F;
        if (angle > 360F)
            angle -= 360F;
        return Mathf.Clamp (angle, min, max);
    }

    void LateUpdate() {
        if (newPos != null) {
            if (transfomTimeLeft <= 0) {
                _transform.localPosition = newPos.position;
                Vector3 camPos = m_camera.transform.localPosition;
                camPos.z = newPos.distance;
                m_camera.transform.localPosition = camPos; //.z = /*Vector3.forward * */newPos.distance;
                newPos = null;
                oldPos = null;
            } else {
                transfomTimeLeft -= Time.deltaTime;
                _transform.localPosition = Vector3.Lerp(oldPos.position, newPos.position, (1f - transfomTimeLeft / transfomTime));
                m_camera.transform.localPosition = Vector3.Lerp(Vector3.forward * oldPos.distance, Vector3.forward * newPos.distance, (1f - transfomTimeLeft / transfomTime));
            }
        }
    }

    void updateCameraState ()
    {
        if (m_camera) {
            if ((AppController.currentControlMode == AppController.CR_CONTROL_MODE.MODE_VR)
                || (AppController.currentViewState > AppController.CR_VIEW_STATE.VIEW_FLOOR))
            {
                m_camera.enabled = (AppController.currentViewState != AppController.CR_VIEW_STATE.VIEW_PANORAMA);
            } else {
                m_camera.enabled = false;
            }
        }
    }

    void controlModeChanged (AppController.CR_CONTROL_MODE mode)
    {
        updateCameraState();
    }

    void changeStage(int stage, CameraPosition np) {
        transfomTimeLeft = transfomTime;
        if (positionStack.Count == stage) {
            // Nothing to do
        } else if (positionStack.Count > stage) {
            // Move m_camera to back position
            if (newPos == null) {
                oldPos = getCurrentPosition();
            } else {
                // Already moving
                oldPos = newPos;
            }
            newPos = positionStack.Pop();
        } else if ((positionStack.Count < stage)&& (np != null)) {
            // Move m_camera to new position
            if (newPos == null) {
                oldPos = getCurrentPosition();
            } else {
                oldPos = newPos;
            }
            newPos = np;
            positionStack.Push(oldPos);
        }
    }

    public void viewStateChanged (AppController.CR_VIEW_STATE state)
    {
        CameraPosition cp = null;
        updateCameraState();
        if (state == AppController.CR_VIEW_STATE.VIEW_BUILDING) {
            changeStage(1, cp);
        } else if (state == AppController.CR_VIEW_STATE.VIEW_FLOOR) {
            cp = new CameraPosition(GameObject.Find("ButtonPoints").transform.position, 80f);
            changeStage(2, cp);
        } else if (state == AppController.CR_VIEW_STATE.VIEW_APARTMENT) {
            cp = new CameraPosition(AppController.viewPointStack.Peek().trans.position, 30f);
            changeStage(3, cp);
        } else if (state == AppController.CR_VIEW_STATE.VIEW_PANORAMA) {
       
        }
    }
}

And 3-rd mine:

using UnityEngine;
using System.Collections;

public class BTNEnterViewFloorState : MonoBehaviour {
    public GameObject GOAppController = null;
    public GameObject m_camera;

    void OnMouseUp ()
    {
        GOAppController.GetComponent<AppController> ().Sanat_ChangeState(2);
        GOAppController.GetComponent<AppController> ().controlModeChanged ();
        GOAppController.GetComponent<AppController> ().updateModelVisibility();
        m_camera.GetComponent<CameraTargetScript> ().viewStateChanged (AppController.CR_VIEW_STATE.VIEW_FLOOR);
    }
}
m_camera.GetComponent<CameraTargetScript>().viewStateChanged(AppController.CR_VIEW_STATE.VIEW_FLOOR);

should be

m_camera.GetComponent<CameraTargetScript>().viewStateChanged(GOAppController.GetComponent<AppController>().CR_VIEW_STATE.VIEW_FLOOR);

you can’t access directly public methods or variables of a MonoBehaviour this way → AppController.CR_VIEW_STATE.VIEW_FLOOR
you have to get the script with GetComponent and than access the publics

also what i would do is →

using UnityEngine;
using System.Collections;
    public class BTNEnterViewFloorState : MonoBehaviour {
    public GameObject GOAppController = null;
    public GameObject m_camera;
    private AppController appControllerScript;
    private CameraTargetScript cameraTartgetScript;

    void Start(){
        appControllerScript= GOAppController.GetComponent<AppController>();
        cameraTartgetScript = m_camera.GetComponent<CameraTargetScript>();
    }
    void OnMouseUp ()
    {
        appControllerScript.Sanat_ChangeState(2);
        appControllerScript.controlModeChanged();
        appControllerScript.updateModelVisibility();
        cameraTartgetScript.viewStateChanged (appControllerscript.CR_VIEW_STATE.VIEW_FLOOR);
    }
}

so if you have to use a script from the same Gameobject more often, you should reference it in Start or Awake so you can access it fast

Also depending on what your AppController is doing you could use it as an Singleton instead of MonoBehaviour

http://wiki.unity3d.com/index.php/Singleton

Thanks for answering!

Did what u wrote, but Unity gave this errors:
Error #1
Assets/ProjectFiles/scripts/BTNEnterViewFloorState.cs(24,75): error CS0572: CR_VIEW_STATE': cannot reference a type through an expression; try AppController.CR_VIEW_STATE’ instead

Error #2
Assets/ProjectFiles/scripts/BTNEnterViewFloorState.cs(24,37): error CS1502: The best overloaded method match for `CameraTargetScript.viewStateChanged(AppController.CR_VIEW_STATE)’ has some invalid arguments

Error #3
Assets/ProjectFiles/scripts/BTNEnterViewFloorState.cs(24,37): error CS1503: Argument #1' cannot convert object’ expression to type `AppController.CR_VIEW_STATE’

Can you post your BTNEnterViewFloorState class again ?
Because the stuff i posted doesn’t use AppController.CR_VIEW_STATE maybe you didn’t changed everything i did?

No, it shouldn’t. CR_VIEW_STATE is an enum. You don’t declare variables of an enum type through an instance of the class it’s defined in.

//You can drag these components in the editor, as well. It doesn't have to just be gameObjects.
//In fact, if you drag the gameObjects that you've already used, this fields should auto-populaet with the correct component.
//The [SerializeField] attribute makes something editable in the inspector. Only use public for a serializale field if other code should access it.
[SerializeField] AppController appController;
[SerializeField] CameraTargetScript cameraTargetScript;

void OnMouseUp ()
{
    appController.Sanat_ChangeState(2);
    appController.controlModeChanged ();
    appController.updateModelVisibility();
    cameraTargetScript.viewStateChanged (AppController.CR_VIEW_STATE.VIEW_FLOOR);
}

^ Pretty close to what you had originally, SHOULD work. The problem is that it’s saying ‘viewStateChanged()’ is not public, so you can’t call it. Which is very strange, because according to the code you’ve posted, it IS public. So is it’s parent class definition and so is the enum definition.

I created a unity project and imported your code. The AppController class you posted obviously isn’t complete, so I just created a bunch of dummy methods so that it would compile. I did not get an inaccessibility error like you’ve shown up top.

Wherever the problem is, it’s somewhere other than this code. I’m having difficulty imagining what would cause an access modifier error from an outside source. Are you sure this code is the same as the code in your project? Is there any possibility of conflicting or ambiguous namespaces?

And, out of curiosity, you say your new company asked you to modify this code. Did they write it, or did they download it from somewhere?

1 Like