I seem to be running deadstraight into wall after wall with trying to figure this out. Searching points me to topics that have either nothing to do with what I want, or ones that I have looked at already.
1 : How do I use variables created outside functions in another file?
2 : What is the difference and limitations of variable types (private, public, ect)
3 : How do I use functions from 1 file in another? What if they are in a different gameobject?
4: What is the difference and limitations of function types (private, public, ect)
Answer by Tetrad
Jul 14, 2010 at 04:40 PM
Everything in one file is in one class. private variables and functions can only be used inside that class. public variables and functions can be used by that class and anything that references that class.
All of your scripts are a subtype of Component. So like how you can do var myRigidbody = GetComponent( "Rigidbody"), you can do the same thing with your classes.
var myRigidbody = GetComponent( "Rigidbody")
Once you have a reference to your custom component type, you can then call functions and access variables just like anything else.
As a basic example:
var counter : int = 0;
counter += 1;
counter += 1;
private function WillNotBeAbleToCallThisExternally()
Debug.Log( "private function" );
In another script that's attached to the same game object as the above is, you can do this:
var myClass = GetComponent( "MyClass" );
var myClassCounter = myClass.counter;
And that should be obvious what that does. However you won't be able to call the private function, or access private variables with a reference to your class.
If that script is on another game object, first you have to get a reference to the game object that your script is on. From there it's the same, you would just call GetComponent on the game object reference itself. You can search by name (bad idea, but what most people start with since it makes the most obvious sense), or you can set up references inside your script and set things up ahead of time in the scene or via instantiation.
Thank you, that explained it perfectly for me.
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.
The best place to ask and answer questions about development with Unity.
To help users post good questions and use the site effectively we have posted a user guide.
If you are a new user, check out our FAQ for more information.
If you are a moderator, see our Moderator Guidelines page.
We are making improvements to UA, see the list of changes.
For troubleshooting common problems with Unity 5.x Editor (including Win 10).
Answers and Comments
No one has followed this question yet.
How faster is private variables over public variables?
public private and static variables in js
Variable value persists when public but is lost between frames when private
When to use private var. and public var.?
RTS Style Selection system (How to control one unit and not the others)