0
votes

So I've been developing Hololens applications with c# and unity and have come across this problem.

Setup that I currently have: GameObject prefab that once instantiated, automatically plays an animation. About two GameObjects get instantiated every second, with a maximum of about 60 staying in the scene before being deleted.

What I'm trying to do: On a button click, stop all the animations on each gameobject.

I've tried creating a script on the prefab using these methods but none have worked:

public void StopAnimation()
{
    anim = gameObject.GetComponent<Animation>();
    anim.Stop();
}

//also tried
public void StopAnimation()
{
    gameObject.GetComponent<Animation>().Stop();
}

//and have even tried destroying the gameobject 
public void StopAnimation(){
    Destroy(gameObject);
}
2
How do you call StopAnimation from the Button?Fredrik Widerberg
"but none have worked" - what do you mean by that? Do they keep animating? Do they disappear? Do they keep instantiating?Rodrigo Rodrigues

2 Answers

0
votes

Since you dont mention the name of the script in the question, im going to call it StopAnimationScript

When you instantiate the prefab, you need to grab the StopAnimationScript-component from the newly created instance.

var stopAnimationScript = newInstance.GetComponent<StopAnimationScript>();

then you need to store this reference somewhere, like in a List<StopAnimationScript>

myStopAnimationScripts.add(stopAnimationScript);

When you press the button, you need to call StopAnimation on every instance

foreach(var stopAnimationScript in mytopAnimationScripts) 
{
    stopAnimationScript.StopAnimation();
}
0
votes

Okay so I actually just figured it out and am now posting it for anyone else that may need it. So basically I deleted the script on the prefab and went to the "StopAnimationButtonScript" that is attached to the Stop button and inserted this code when the button is pressed:

public void StopAnimations()
{
        foreach (GameObject CloneObject in GameObject.FindGameObjectsWithTag("*insert a custom tag like 'Clone'*"))
        {
            if (CloneObject.name == "*insert actual game object name here*")
            {
                CloneObject.GetComponent<Animation>().Stop();              
            }
        }
}

Then go to your clone prefab and give it the tag 'Clone' or your own custom tag located directly below the name of the object in the inspector panel.

Thank you to everyone that helped!