Why can I change the private variable ?

Hi everybody ! Today when I writing code, I found a interseting thing is that I can change the private variable from the prefab’s script. everybody say the private variable can’t be changed, but why can I change it ? can you explain it for me ? I’m really get confused.

the prefabs code(does not put on the scene):

the emptyObject code(already on the scene):

“private” doesn’t mean that it can’t be changed. It only means it can be changed from within the declaring script.

I’m not sure if the two chunks of code you posted are located on the same script or not. If they’re on the same script, then you can change xPos/yPos. If they’re on two different scripts, maybe this is an issue with JavaScript’s dynamic typing? Also, try to double check that the values are actually assigned; perhaps this is compiling but at runtime no changes are passed:

ball.GetComponent(“MoveBall”).xPos = new_xPos;
ball.GetComponent(“MoveBall”).yPos = new_yPos;
Debug.Log("New position set? " + ball.GetComponent(“MoveBall”).xPos);

Hi FizixMax!

They’re two different scripts. I think it maybe changed by JavaScript’s dynamic typing. Thanks for you answer. :slight_smile:

In that case, try using the generic overload of GetComponenet:

var moveBall : MoveBall = ball.GetComponent.<MoveBall>();
moveBall.xPos = new_xPos;
moveBall.yPos = new_yPos;

In general, the more strongly typed your code is, the better.

yea ! I’m really learn something useful skill, thx you FizixMan :slight_smile:

Also, if you want a variable hidden from the inspector but to be accessible by other objects, you can make a public variable but precede it with the @HideInInspector tag.

EDIT: Ohh I just realized you said CAN, not CAN’T, sorry :slight_smile: