Assign GameObject Inspector Vars Via Script

Context: I have a desk chair in my game. This desk chair consists of two separate models (seat & base). I have an animation attached to the chair that makes only the seat spin. I want this animation to play when the user clicks on EITHER the chair OR the base. Therefore I have written a “Best Friend” script that allows me to make relationships between these objects. Whenever the player clicks on an object, it looks for any “Best Friends” and runs any animations on those best friends. It works great!

Problem: My problem is that every time I update and re-import my scene, unity erases all my inspector-made (drag&drop) connections and there are a lot of them in my scene. Therefore I am trying to automate this drag&drop relationship process. I figured I could do this easily with GameObject.Find and GetComponent in an Editor Script or at Runtime but I keep getting Null Reference Exceptions in both cases. My script is below…

function Awake ()
{
    	// Set All Best Friends
    	GameObject.Find("Chair2/Chair").GetComponent(VocabWord).bestFriendA = GameObject.Find("Chair1/Chair");
}

Use Find at Start, not Awake - Awake is called during object creation, and some objects may not exist at that time. Another point: I have not tested this yet, but suspect that paths like “Arm/Hand/Finger1” only work in Transform.Find, not in GameObject.Find - Transform.Find only searches in the object’s children, while GameObject.Find searches in all the scene objects. In the example above, use GameObject.Find(“Arm”) to locate the arm, then call arm.Find(“Hand/Finger1”).

The Null Reference Exceptions most likely means that either GameObject.Find() or GetComponent() is not returning anything so I would check to make sure your syntax is correct and that your names are all set up correctly. I might also try putting your code in in Start() rather than Awake() if possible.

I would look at the various ways you can access other game objects. You can find a pretty good reference/overview here

There might be an easier way to do it, via the hierarchy perhaps.