Transferring values from one script to another script?

I have looked around but haven’t found anything that helped me quite yet, just for a test I made a scene with a camera that shot a cube at a wall. What I want to test is that after a couple hits the wall should disappear/break. Here’s what I had on the bullet so far, I need a way to transfer the values from this script to my wall/playerproperties script.

Bulletcollision.js:

   var damage = 5;
function OnCollisionEnter(theCollision : Collision){
 if(theCollision.gameObject.name == "Wall"){
 

}

Playerproperties:

var health=20;

function Update()

{

if (health <= 0)
destroy(gameObject);

}

Assistance would be great, thanks ahead of time

  • Valestrom

Hi There It's not entirely clear to me what you are trying to do, but it strikes me that a script on your wall should track its own health and do the deduction/destruction. Please post more details! H

2 Answers

2

very simple the scripts are attached to a game object so you would want to say something like

//this line is in the playerproerties script
public GameObject obj1; //drag the object with the bullet collision script on this

then you can say something like this:

obj1.GetComponent<Bulletcollision>().<YOUR VARIABLE NAME HERE> = <VALUE>;

Unfortunately I’m not incredibly familiar with javascript so this is written in C# but you should be able to convert it fairly easily.

Hope that helps :smiley:
Hans

For completeness, js would look like: obj : GameObject; obj1.GetComponent.< Bulletcollision >().<var name here> = <value here>;

Thanks Joshua :)

var damage = 5;
function OnCollisionEnter(theCollision : Collision){
if(theCollision.gameObject.name == “Wall”){

//take 5 points from health of the wall
Player.health -= damage;

}

Player.js /// Iam assuming the name of the file is Player
static var health=20;

function Update()

{

if (health <= 0)
destroy(gameObject);

}

// notice the word static before health variable
you can update static var across files.

This answer is technically correct, but when some one asks how to reference other scripts and instead you tell him to use static variables - that's usually only confusing. And it won't work if he has several players.