I am pretty new to scripting in javascript and i seem to have gotten down some of the basics. I do not understand however how to allow different scripts or variables to interact with one another. At the moment i need to make a player inventory but i do not know how to allow for the 2 scripts to interact with one another. Thanks in advance
There are 3 ways to access other script members:
-|-Static, make the variable static and you can access it with the scriptname and the var name
Player.js
static var health:int;
anywhere:
Player.health-= damage;
Pros: Easy to use. Cons: Static means only one instance of the variable exists, meaning that if you have a static for enemy health, they all die at once. It is fine though for player health, player score, enemy counts or anything that is only once in the game.
-|-GetComponent, you can access other script with GetComponent like this:
var other : ScriptName;
other = gameObject.GetComponent("ScriptName");
other.someVariable = 5;
Better is to cache if the action is used often
var other : ScriptName;
function Start(){
other = gameObject.GetComponent("ScriptName");}
function Update(){
other.someVariable = 5;}
if the script belongs to another object:
var other : ScriptName;
function Start(){
other = GameObject.Find("ObjectName").GetComponent("ScriptName");}
function Update(){
other.someVariable = 5;}
Pros:works for all variables and functions of any types (or almost). Cons: takes a little work and understanding at first. A little exepensive if not cached.
-|-SendMessage(), you can simply send a message to an obejct to tell him what to do.
anywhere
GameObject.Find("OtherObject").SendMessage ("Dosomething");
//If the script is on the same object(gameObject. is actually not compulsory)
gameObject.SendMessage ("Dosomething");
another script
function Dosomething(){
//Do smg;}
if the function requires parameter, they are passed in the parenthesis as such:
GameObject.Find("OtherObject").SendMessage ("Dosomething",10,20);
function Dosomething(a:int, b:int):int{
return a + b;}
Pros:quite easy to use and straightforward. Cons: Really expensive, not to be used when the action is repeated.
-|-BroadcastMessage(), works the same as SendMessage(). BM sends the message to the object and all children of the object. If they all hold a script everyone will react. SM only affect the targeted object.
Pros and cons are similar to SendMessage except cons are multiplied by the amount of children.
EDIT: I added cases for GetComponent and SendMessage when the script is on another object and Broadcast Message.