# Calling a function from another script.

**URL:** https://discussions.unity.com/t/calling-a-function-from-another-script/397274
**Category:** Scripting
**Tags:** Scripting
**Created:** [August 30, 2009, 12:56pm UTC](https://discussions.unity.com/t/calling-a-function-from-another-script/397274 "2009-08-30T12:56:49Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![anon\_40706304](https://avatars.discourse-cdn.com/v4/letter/a/ebca7d/32.png) [@anon\_40706304](https://discussions.unity.com/u/anon_40706304)
#### Post date: [August 30, 2009, 12:56pm UTC](https://discussions.unity.com/t/calling-a-function-from-another-script/397274/1 "2009-08-30T12:56:49Z")

</div>

I store my game objects in an array:

targetArray.Push(targetPrefab);

Now I randomly select one of the game objects from the array using:

targetArray[random(0,targetArray.length)];

How can I call a function that is on the game object in the script myScript?

---

<div class="post-metadata">

### Author: ![anon\_57407815](https://avatars.discourse-cdn.com/v4/letter/a/bbce88/32.png) [@anon\_57407815](https://discussions.unity.com/u/anon_57407815)
#### Post date: [August 30, 2009, 1:51pm UTC](https://discussions.unity.com/t/calling-a-function-from-another-script/397274/2 "2009-08-30T13:51:19Z")

</div>

> [@""](#):
>
> I store my game objects in an array:
> 
> targetArray.Push(targetPrefab);
> 
> Now I randomly select one of the game objects from the array using:
> 
> targetArray[random(0,targetArray.length)];
> 
> How can I call a function that is on the game object in the script myScript?

You need to

```auto
var somInstance : SomeClass = targetArray[random(0,targetArray.length)].GetComponent(SomeClass);
someInstance.SomeFunction();

```

or a better approach would be to store the instances you need in an array (preferably a builtin array ) and then just call the function

```auto
var targetArray : SomeClass[];
targetArray = new SomeClass[someSize];
--- assign the scripts ---
targetArray[random(0,targetArray.length)].SomeFunction();

```

that way you don’t need to call GetComponent and builtin arrays are much faster than Array.
