- Home /
Using a Variable over two Scripts
I have 2 scripts... one for the player and one for the enemy...
i want now a vector3 variable in the enemy script, that i can also use in my player script...
how can i do that?
if the variable changed in the enemy script, it must also changed in the player script....
i hope someone can understand me :/
Answer by Linus · Jul 28, 2013 at 03:27 PM
playerScript.js
var enemy : enemyScript; //Type is the name of the script
function Start(){
enemy = GameObject.Find('enemy').GetComponent(enemyScript); //The game object where enemyScript is attached is named enemy
//All public variables and functions on that script is now available from the enemy variable.
enemy.someVector = Vector3(10,10,10);
}
enemyScript.js
//The variable needs to be declared inside this script
var someVector : Vector3;
This will set the var someVector to 10,10,10 on start.
Do read the manual http://docs.unity3d.com/Documentation/Manual/Scripting42.html
is there a way to get the script without finding a gameobject?
Sure there are, how do you want to get it? If your reason is that you have read that .Find is slow, its not a problem at all when only done once it Start()
the problem is that the script on every enemy is... and i can only find the script of one enemy...
i want the script of the enemy i tag with the mouse for example... through a ray cast and a hit collider or with mouseover... ??
Web Search: GetComponent on clicked object Here is one previous answer on this http://answers.unity3d.com/questions/228974/enemy-select.html
Answer by sfc.itzhak · Jul 28, 2013 at 03:19 PM
you can either use 1 static variable: http://answers.unity3d.com/questions/321385/static-variables.html
or use public variables and create a function that will upadate all other scripts //not recomnded.
or create 1 manger that holds the varibale and all scripts take the values from it (almost like a static var)
sfc
Answer by Akinup · Jul 28, 2013 at 03:48 PM
hmm... i do not really understand how static helps me :/
i have the variables:
public Vector3 enemy; public Vector3 reset;
in the Script "Enemy"
but even with Enemy.enemy or Enemy.reset, the Script "Player" doesn't find it...
please consider to convert this to a comment. Its how Unity Answers rolls.
Answer by Rs31412 · Feb 18, 2014 at 06:57 AM
For those doing C# I found this following code to be the way to work.
public int myVariable;
GameObject myObject = GameObject.Find("objectInHeirarchy");
myVariable = myObject.GetComponent<myObjectScript>().myVariable;