- Home /
Replacing animations from a list at runtime
I have a class that contains a List of GameObjects called Characters which are set during design. The GameObjects are prefab images. I use the following line of code to instantiate the initial image:
Instantiate(Characters[0].Image.GetComponent<Transform>(), CharacterImage.position, Quaternion.identity, CharacterImage.transform);
I then have a button to click to advance through the list. What I'd like to have happen is the old animation to be replaced by the next animation in the List. What happens is that it keeps creating the animations one on top of the other. I then attempted:
Destroy(CharacterImage.transform.gameObject);
but then the next image in the list can't load (or at least it doesn't show...even with another call to instantiate.
So in short...I have a list of a class that contains an animation GameObject. I would like to click a button and display the corresponding animation from that list while removing the previous animation from the screen. This is all in the UI, btw. Here's a screen shot of the inspector for the class where I set the animations for the List. Any help appreciated
Answer by logicandchaos · Jan 19, 2021 at 03:38 PM
When you instantiate you create a new object from a template, then you set its position to CharacterImage.position and parent CharacterImage.transform. When you use Destroy(CharacterImage.transform.gameObject); you are destroying the CharacterImage object, not the newly instantiated object, you can't make a new object at CharacterImage.position, parented to CharacterImage.transform because you destroyed CharacterImage.
There are a few ways to solve this. You can make a reference to the new gameObject,
//instantiate like this so you have a reference to the new
GameObject frame=Instantiate(Characters[0].Image.GetComponent<Transform>(), CharacterImage.position, Quaternion.identity, CharacterImage.transform);
//then to destroy
Destroy(frame.gameObject);
Or instead of instantiate and destroy, create all the objects in your scene and disable them all, then enable and disable them as necessary.
I did as you suggested and am using an Activate/Deactivate. But now I'm using if statements and tags instead of the List: if(_ci.Description.Contains("Female Warrior")) { WarriorImage1.gameObject.SetActive(false); WarriorImage2.gameObject.SetActive(true); } else { WarriorImage1.gameObject.SetActive(true); WarriorImage2.gameObject.SetActive(false); }
Is there a way to utilize the list?
Thanks for the quick reply, btw. Very nice!