Wednesday, January 14, 2015

Unity script referencing



I wanted my keyboard input script to retrieve a value from a grid generator script so it knew how far to move one of my game objects. It took me a while to figure it out even though it's simple so I figure it's best to leave myself a bread crumb so I don't have to search so much next time.

//this is how you get a reference and value out of another script
scriptholder = GameObject.Find("EmptyScriptHolder");
GridManager script = scriptholder.GetComponent<GridManager>();
print("Grid gap =" + script.stepsize);


This shows how to get a reference to the actual script, in this case it's my EmptyObject I use to hold scripts that are not associated with actual GameObjects.  I call it EmptyScriptHolder.  I then get the reference to the GridManager script.  This is the actual type name of the script.  Within that script is a method variable called stepsize.  Overall it's very simple to get a value out of another script once you know how to do it.

This site was very helpful even though it's documentation from a few versions back.
http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

No comments: