- Home /
Passing variables between classes attached to different GameObjects
As I said above, I'm trying to pass a variable from one class to another, however I can't use GetComponent() the reason being that the two classes aren't attached to the same GameObject. I have no idea how to get around this, and I need this to work in order for object1 to check if object2 (instantiated by object1) is destroyed.
object1 passes a boolean true if the fire button is pressed. I want it to pass a boolean false if float x (in object2) = 0. When object2 is instantiated float x = 1;
if the bool is true, object1 is no longer functional, once false and object2 is destroyed object1 should become functional again.
Answer by jogo13 · Dec 09, 2012 at 05:11 AM
You can 'grab' another GameObject (and then use GetComponent) with: http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html
It's a little slow and it's considered bad practice to call every frame (It's better to use it once and save the reference.)
GameObject reference = GameObject.Find("object2_name");
I can just save that in void Start.
I'm seeing now that there are two GetComponent functions. One is Component.GetComponent and the other is GameObject.GetComponent. I may have been using the first one lol.
Answer by landon912 · Dec 09, 2012 at 04:54 AM
You will probably not like the answer the best because it isn't what you ask for exactly, but I want you to have to edit it and therefore understand instead of copying and pasting into your game and not looking at it. Below is all the info needed to complete what you want.
How I do it(may not be the best or easiest):
var gameobject1:GameObject;
var gameobject1Script: Script ///Change to the name of the script you are trying to get the var from
function Start(){
gameobject1=GameObject.Find("Object1"); ///Change to name of the object the script is attached to.
gameobject1Script = gameobject1.GetComponent(Script); ///Change to the name of the script you are trying to get the var from
}
function Update(){
if(gameobjectScript1.dead == true)
Debug.Log("Death");
}
Wait, I now think of that I think you want C#. since class is hidden from the user in JavaScript. Pm if you need me to translate
I am using C#, but I can translate it. Sometimes it's just difficult to find the correct function to use in the script ref lol.
mk, just so you know this also works getting var from UnityScript to a C# script