Calling protected variable from another class

Viewed 338

I need to call a protected variable from a public class into an if statement in a private method of another public class I am programing a video game in unity and I need to use a bool variable (that shows if the character is out of stamina) in an if statement to determine whether or not the character can run This is what my code looks like excluding everything unrelated to the problem

Public class CharacterStats : MonoBehaviour
{
[SerialzeField] protected bool Tired;
}

Public class PlayerMovement : MonoBehaviour
{
Private void HandleRunning()
 {
 If (Input.GetKeyDown(KeyCode.LeftShift) && X != True) 
  {
 Speed = RunSpeed;
  }
 }
}
X is where I want the Tired variable to be.   
1 Answers

Use a public readonly property like e.g.

public class CharacterStats : MonoBehaviour
{
    // Keep you serialized field protected
    [SerialzeField] protected bool tired;

    // Have a public read-only accessor property
    public bool Tired => tired;
}

and then e.g.

public class PlayerMovement : MonoBehaviour
{
    // Somehow you will need to get a reference to the CharacterStats instance
    // e.g. via the Inspector
    [SerializeField] private CharacterStats stats;

    [SerializeField] private float RunSpeed;

    private float Speed;

    private void HandleRunning()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift) && !stats.IsTired) 
       {
           Speed = RunSpeed;
       }
    }
}

Alternatively (and my apologies to @aybe who had answered this) you can actually directly serialize a property using explicitely

[field: SerializeField] public bool Tired { get; protected set; }

this is a property which can be accessed by everyone but only this and inherited classes (and due to the serialization now the Inspector) have the permission to set the value.


In general: Fix your casing! In c# all keywords are lower key!

Related