- Home /
Is it possible to get two scripts from different objects to talk to each other without assigning objects in the inspector?
Ok, for reference I'm doing a spaceship game in Boo. I have a ship, it is parent to a camera and an empty that acts as an anchor point for a weapon of the player's choice. Each of these potential weapons has a script that needs a variable from a script running on the camera.
Now in my 1st prototype the anchor point empty was actually the weapon itself and was fixed, unchanging. As such I could use:
public Targetscript as Targeting1
public Gpos as Vector3
def update():
Gpos = Targetscript.GunneryPOS
where Targeting1 is the name of the script attached to the camera, and GunneryPOS is the variable I need to pull. Drag and drop the camera to Targeting1 in the inspector and everything was happy. Now however, with swapping out weapons and possibly having multiple ships I feel like the drag and drop to the inspector is not particularly flexible.
I feel like the answer I'm looking for has something to do with transform.root and/or transform.Find(). I want to say "Hey weapon, you are now part of a ship. Go look for the camera that's also part of the ship and pull GunneryPOS from Targeting1." I'm just not sure quite how.
Answer by by0log1c · Mar 03, 2011 at 04:16 AM
I'm more familiar with JS but I've used Unity scripting reference to write it in BOO(quite similar after,all?) after reading Peter's comment, here's an example:
//for a specific instance on a specific GameObject: Targetscript = GameObject.Find('theGameObjectName').GetComponent[of Targeting1]();
//or : Targetscript = FindObjectOfType(Targeting1); Targetscripts = FindObjectsOfType(Targeting1); //also works
AFAIK, .Find and .GetComponent are considered slow only if used repeatedly. The idea is to store the result in a variable like the example above.