- Home /
How do I add/subtract variables between two different JavaScripts?
I know the question isn't worded very well so, I'll elaborate.
Say if the player is trying to destroy an object like a soda can for the sake of the question.
On one script the soda can has a variable for health say 100.
Then on the player script it says that if this has a tag or so of "Junk" Then deal this value of damage and subtract it from the health of the Soda can.
I'm under the impression this has something to do with broadcasting, but I tried and I have no clue.
*None of the scripts below are existent yet this is just for future reference.
SodaCan.js
var health : int = 100;
function Update(){
curHealth;
}
Player.js
var junkDamage : int = 50;
var junkObj : GameObject;
function DestroyJunk (){
if(junkObj.tag == "Junk"){
DealDamage()?;
}
function DealDamge(){
var curHealth = health - junkDamage;
}
I am aware that this is no where at all accurate. I just need to know the logic behind it so I may apply it.
Answer by YoungDeveloper · Dec 16, 2013 at 02:12 AM
You must getcomponent from soda somehow from the player first, there are many possibilities, via Ontrigger, OnCollision, raycasting, and many other. You should choose the best method which fits your needs. But for showing you, i will be using the simplest method- that is accessing gameobject you have added via inspector.
Player.js
var damage : int = 50;
var sodaCanObject : GameObject; //Attach the gameobject with **SodaCan.js** in inspector
function Start(){
//First we need to get the soda script itself from sodaCanObject
var script : SodaCan = sodaCanObject.GetComponent("SodaCan");
script.DealDamge(damage);
}
SodaCan.js
var health : int = 100;
public function DealDamge(damage : int){
health -= damage; //same as health = health - damage;
}
Thank you! I appreciate for someone explaining it other than giving just the code so I may use it for future projects. If I had 15 rep to up vote you I would.
No problem, some day you will come back, and up vote ;-)
Your answer
Follow this Question
Related Questions
Can't get var from other script. 1 Answer
C# GetComponent Issue 2 Answers
Use variable from another script with WWW give NULL? 1 Answer
Calling A Method From Another Script in C Sharp 3 Answers
How to make a third person free raom? 2 Answers