Calling Functions From Another Script

Hi

Title pretty much says it all. How can I call a funtion thats in a different script (in C#)?

Heres my setup:

Script 1:

public class BipAnimScriptSegments : MonoBehaviour {

public void ArmAnimation(){		
		animation.CrossFade("Arm");		
	}
	
	public void LegAnimation(){
		animation.CrossFade("Leg");
	}
}

Script 2:

public class GUIScript : MonoBehaviour {

public BipAnimScriptSegments target;
		
	void OnGUI () {
		GUI.Box (new Rect (10,10,100,90), "Animations");

		if (GUI.Button (new Rect (20,40,80,20), "Arm")) {			
			target.ArmAnimation();
		}
	
		if (GUI.Button (new Rect (20,70,80,20), "Leg")) {
			target.LegAnimation();
		} 
	}	
}

When I click a button in the GUI I get the follow error: “Object reference not set to an instance of an object” and it points to “target.ArmAnimation();”.

What am I missing here?

Thanks.

Have you assigned the script to ‘target’ variable via inspector? Ie. dragged the GameObject containing BipAnimScriptSegments script to the ‘target’ field of GUIScript ?

Omg, thank you! :smile: I never saw that before.

Is there any way to do this kind of association by code? Or is it only in Unity drag-drop that this can happen?

Also, slightly related question; when Raycasting for GameObjects (like when moving mouse to select objects), won’t Physics.RaycastHit.collider.gameObject.SendMessage have the same effect as what the asker is trying to acheive? Namely; to access a GameObject instance’s script specific functions?

Yes to whether it’s the same, although you can only pass one variable and you can’t assign things to its return value. You can gain access to the script using gameObject.GetComponent(ScriptName);