Hi Unity Community! I’m relatively new to Unity and my experience in OOP is not quiet strong.
I’m trying to make a class, say BaseClass.cs, and a derived class from it, say DerivedClass.cs. I made some protected
level variable on BaseClass.cs, one of them is List colliders
. While other variable that has a type of int, float, etc. can be accessible from DerivedClass.cs, Unity returned an error when I tried to access colliders
variable (`BaseClass.colliders’ is inaccessible due to its protection level).
While I can fix this error by changing its protection level to public
, this leaves me a question. Why can’t I access my protected List<> variable from my derived class? Shouldn’t protected variables on a base class be accessible to its derived class?
Thank you in advance.
Here are some part of my code:
BaseClass.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class BaseClass : MonoBehaviour {
protected float f; //No error
protected List<Collider2D> colliders; //Error. Changing this to public solved the problem
protected void Awake()
{
colliders = new List<Collider2D>();
}
// Use this for initialization
protected void Start () {
//Some other code
}
// Update is called once per frame
protected void Update () {
if (Input.GetMouseButtonDown(0))
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit.collider != null && hit.collider.name == name)
{
foreach (Collider2D coll in colliders)
{
//Set collided gameobject's parent to this gameobject
coll.transform.parent = gameObject.transform;
}
//Do something
}
}
}
protected void FixedUpdate()
{
//Do Something
}
protected virtual void OnTriggerEnter2D(Collider2D other)
{
if (!colliders.Contains(other))
colliders.Add(other);
Debug.Log(colliders.Count);
}
protected virtual void OnTriggerExit2D(Collider2D other)
{
if (colliders.Contains(other))
colliders.Remove(other);
Debug.Log(colliders.Count);
}
}
DerivedClass.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DerivedClass : BaseClass {
protected void Awake()
{
base.Awake();
}
// Use this for initialization
void Start () {
base.Start();
}
// Update is called once per frame
void Update () {
base.Update();
}
void FixedUpdate()
{
base.FixedUpdate();
}
protected override void OnTriggerEnter2D(Collider2D other)
{
base.OnTriggerEnter2D(other);
//Here's where I use protected List<Collider2D> colliders from BaseClass.cs
foreach (Collider2D col in colliders)
{
//Do Something
}
}
}