1
\$\begingroup\$

I have a GameObject that is a Farmer that plants Seeds. The Seeds will animate into Plants. Once that animation is complete, I'd like to replace my Seed with a Plant. This happens hundreds of times per game at arbitrary positions. I've tried this as something I built off of this question: Unity: detect animation's end

public class SeedScript : StateMachineBehaviour {
[SerializeField] private GameObject seed;
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
    Destroy(this);
    animator.GetComponent<TreeScript>().GrowTree(seed);
    Instantiate (tree, this.position,  this.rotation);
}

}

Obviously, this doesn't work at all. Doesn't even compile.

I've also looked at these co-routines: https://answers.unity.com/questions/981948/statemachinebehaviour-startcoroutine.html but again, I need to get position data from the animating object.

Yes, I could just merge my Seed and Plant classes together, let's pretend I cannot do that and MUST instantiate some arbitrary new object at the position of another object on some animation completion.

\$\endgroup\$
1
\$\begingroup\$

this in your code would refer to the StateMachineBehaviour so if you Destroy(this) you try to destroy the wrong object.

Rather add an event to your animation timeline that calls a method on your Seed GameObject (attach the script to your GameObject). The benefit of this approach is you can move your event to any position on your timeline, for example you might want to show the seed and plant simultaneously so that it looks like the plant is coming out of the seed.

Inside that method (on your Seed GameObject), you can Instantiate your Plant script (attach the script to your Plant GameObject) and copy your variables from the Seed GameObject to your Plant GameObject.

enter image description here

public class Seed : MonoBehaviour
{
    public Plant plantPrefab;

    public void GrowPlant()
    {
        Plant plant = Instantiate<Plant>(plantPrefab);
        plant.transform.SetParent(transform.parent);
        plant.transform.SetPositionAndRotation(transform.position, transform.rotation);

        // Whatever else you want to copy...
    }
}
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.