What is happening in Code (C#)

I am trying to learn how to make a Master Script / GameObject give orders to a Slave Script / GameObject and then have the Slave report back. For the most part I believe I got it working, but I have to drag and drop the object to there fields in the unity editor and I want the script to find it automatically through code. I also want the Master to be able to have multiple slaves.

alt text

When I drag and drop the game object on to the field what is happening in code? I am using C# and here is my code.

alt text

Download The File

When you drag and drop the object you are causing the public variable to be changed to the value of what you drop onto it. The field is public, so that info is serialized and stored in the scene. You could set the value “reportBack” in code just as easily, such as:

reportBack = (Slave)GameObject.Find(“SomeObject”);

You can do this in an initialization step, on Start, or at other points in script execution depending on when it makes sense. There are many ways to do this actually. See the script reference for more info.

Unity will automatically serialize public fields from your MonoBehaviour scripts, such as those object references. The inspector is able to get/set those values in the editor; Unity will also save those values with the scene, and restore them when the scene is loaded.

That is a pretty complicated process, as you can probably imagine.

If you want to set those references up in code, you can probably use lookup functions like GameObject.FindGameObjectsWithTag(), GameObject.GetComponent(), GameObject.AddComponent(), and so on. It’s pretty common to perform quite a few of those lookups during Awake() calls.

Unity’s script reference has some helpful information on this topic: