Accessing variables and enum from an external script

Hi Unity users,

I am learning Unity and C# at the same time and so far so good. However, I have a doubt related accessing a script from another. The issue I have is, the script I want to access is going to be attached to my player object. So, some variables will be public and other private. Those public variables can be access from the editor and from external scripts and that is ok. But, I want to access also the private variables from an external script.

For instance, this is the script attached to the player object and the one to be accessed from another script

public class AnimationHandler : MonoBehaviour 
{ 
private int currentFrame; 
public int finalFrame;
enum AnimationStates {Stand, Walk, Melee}
}

From the external script I have

objPlayer = (GameObject) GameObject.FindGameObjectWithTag("Player");
scriptAnimation = (AnimationHandler) objPlayer.GetComponent(typeof(AnimationHandler));

I can do this

scriptAnimation. finalFrame = 2;

But I cannot do the same with currentFrame because it is private and I do not want to make it public because I do not want to change it from the editor

I have the same problem with enum. How I can access enum from the external script?

Thanks in advance for your help

use internal instead of private. I don’t know but i have being using it for a while now.
so

internal float someVar;

Then when you use GetComponent() you can access someVar.

Thanks zine92. It worked!!! Now I have to figure out how to access the enum. Any idea?

Thanks in advance

hey learner, to access an enum from another script you must to declare first a var to call it… :

let´s say your script (where enum is) is called “enumScript.js”

enum PlayerActions{
  walk = 0,
  run = 1,
}
static var playerAction : PlayerActions;

then, in your another script :

var enumCalls;

function Awake () {
enumCalls = GameObject.Find("GameObjectContainingTheScript EnumScript.js").GetComponent("enumScript");
}

function CheckPlayerState(){
if (enumCalls.playerAction == "PlayerActions.walk){
  //Make something
  }
}

Thanks for the answer Mig. I was doing something similar but i did it work.

This is the script I call externally

public enum AnimationStates {Stand, Walk, Melee}; 
internal AnimationStates animationStates;
internal int animationToPlay;

And this is the script I use to call enum

objPlayer = (GameObject) GameObject.FindGameObjectWithTag("Player");
scriptAnimation = (AnimationHandler) objPlayer.GetComponent(typeof(AnimationHandler));
scriptAnimation.animationToPlay = (int) scriptAnimation.animationStates.Walk;

Thanks in advance for the help

Well, I solved it but I do not know if it is the right way to do it. I just put enum declaration out of the class and now I can access it directly from any script.
Is this approach correct?

Thanks for your help

don´t worry, if it worked fine, then you´re right, there are many ways to do something :wink: