Mads Christian Sidenius Mads Christian Sidenius - 2 months ago 15
C# Question

Run function/script in another script

I havd tried very hard to access and call a script's function from outside of the script.

----- this is inside a c# script attached to an animating sprite

public class example : MonoBehaviour {
void RunZebra() {
Zebra other = GetComponent<Zebra>();
other.RunIt();
}
}


------ Zebra script attached to a sprite anim

public class Zebra : MonoBehaviour {
public void RunIt() {
// action starting animation

}
}


But it does not execute for some reason?

I need to access and set ScriptName's variable so it's animation state is changed.

Any help and I'll be a happy man.

Answer

I think I get the problem now. So you have some script named example attached to some GameObject man and one or more GameObjects that have the script Zebra attached to it. You want to execute the Zebra.RunIt method for each Zebra object by the RunZebra method of the man object.

To accomplish that you have to adapt the example script.

I suggest you use a public array of Zebra variables in the example script attached to the man GameObject. Then you can drag'n'drop each Zebra GameObject via the Unity3d editor UI into that array property field of the man object´s example script. (I named it ZebraGameObject below. You might have to set the Size property of the ZebraGameObject property first in the UI to the count of Zebra objects).

Then the Unity3d engine automatically gets references to each Zebra script for the example script from the previously set objects, so that the RunIt method can get called.

Nothing to change for the Zebra script assuming the code in // action starting animation is correct.

Here is the example script with the necessary adaptations.

using UnityEngine;

public class example : MonoBehaviour {

    public Zebra[] ZebraGameObject = null;

    void RunZebra() {
        if (ZebraGameObject != null){
            for (int i=0; i<ZebraGameObject.Length; i++){
                ZebraGameObject[i].RunIt();
            }
        }
    }
}

That method works great if the Zebra objects do not get spawned dynamically but are created at design time. If you need to handle dynamically created Zebra objects, then you might want to look into the GameObject.FindObjectsOfType method or maybe the GameObject.FindObjectsOfTypeAll method.