Play/Stop animation/animator on instantiated object - c#

I'm developing a unity game and basically, I have a prefab with a sprite inside it. I created an animation attached to that sprite.
FrogPrefab
|__ FrogSprite
I created a script with a public field "prefab" where I pass my prefab.
My question is, how can I stop and play this animation from my script.
I instantiated my prefab from my start method...
public GameObject gameCharacterPrefab;
private GameObject frog;
void start() {
frog = (GameObject)Instantiate(gameCharacterPrefab, objectPoolPosition, Quaternion.identity);
}
I'm trying to do something like that...
frog.animation.stop();
appreciate any help

First, note that the function should be called Start not start. Maybe this is a typo in the question but it's worth mentioning.
Use GetComponent to get the Animator or Animation component. If the animation is a child of the prefab then use GetComponentInChildren.
If using the Animator component:
public GameObject gameCharacterPrefab;
private GameObject frog;
Vector3 objectPoolPosition = Vector3.zero;
Animator anim;
Instantiate the prefab
frog = (GameObject)Instantiate(gameCharacterPrefab, objectPoolPosition, Quaternion.identity);
Get the Animator component
anim = frog.GetComponent<Animator>();
Play animation state
anim.Play("AnimStateName");
Stop animation
anim.StopPlayback();
If using the Animation component:
public GameObject gameCharacterPrefab;
private GameObject frog;
Vector3 objectPoolPosition = Vector3.zero;
Animation anim;
Instantiate the prefab
frog = (GameObject)Instantiate(gameCharacterPrefab, objectPoolPosition, Quaternion.identity);
Get the Animation component
anim = frog.GetComponent<Animation>();
Play animation name
anim.Play("AnimName");
Stop animation
anim.Stop();

For playing animation we can use Play() but for stopping the animation the Stop method is become obsolete in Unity 2019 or higher versions. So, For disable animation we can use enable flag and set it to false.
//For playing the animation
frog.GetComponent<Animator>().Play();
or
frog.GetComponent<Animator>().enable = true;
//For stop the animation
frog.GetComponent<Animator>().enabled = false;

Related

2d Animation not playing second scene

I created a new animation for meteor GameObject , the animation functions in first scene normally, but the second scene is not playing regularly:
video explanation of the problem
I think the reason for this problem is timeScale , and I added this code from meteor object:
void Start()
{
Time.timeScale = 1f;
}
The problem is not fixed by this.
Animations are triggered by setting the value of an Animator object.
I.E.
[SerializeField] Animator anim;
void SetFields()
{
anim.SetBool("flagName", true);
anim.SetFloat("flagName", 0);
anim.SetInteger("flagName", 0);
}
In your first screen, you must have some script that is setting the field of your meteor animator which has not been added to your new scene

Shooting animation in Unity

I'm creating shooting in Unity, I've set up everything but the problem is that I want the animation to play only on single click but in my script it plays animation infinitely while holding the button. Check the script below. Thanks.
public GameObject bulletPrefab;
public Transform firePoint;
private Animator anim;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
anim.SetBool("isShooting", true);
}
if (Input.GetKeyUp(KeyCode.Space))
{
anim.SetBool("isShooting", false);
}
}
Set 2 States with just Keys on time = 0 the end position Shooting and the end position idle. From idle to shooting with a trigger parameter. From shooting to idle just a time transition. Ps shooting can be done with multiple frames too. Hope it helps.

Unity: Can't access Childrens SpriteRenderer.enabled

I have problems accessing the enabled variable in children of my Player GameObject.
-Human holds Rigidbody2D, BoxCollider, PlayerController script and Animator
-body and range_attack_body only hold SpriteRenderer
What I want to do:
I want to change the SpriteRenderer of my Player Object when mouse button is on hold. There are SpriteRenderers in body and range_attack_body. Both GameObjects are part of animations.
body.SpriteRenderer is active and range_attack_body.SpriteRenderer inactive during normal motion.
In my PlayerController script I wrote a routine that will trigger an attack animation when mouse button is on hold. In this routine I wanted to change the enabled states of the SpriteRenderers. However nothing is happening, meaning the varibales are not changing during runtime. I already checked if the GameObjects and SpriteRenderers are accessed correctly during Awake() and I can find both renderers in my SpriteRenderer array using debug messages.
On top of that I checked what happens if I add a SpriteRenderer to my Human GameObject. It will appear in my SpriteRenderer array and I have full access to enabled variable meaning I can change them in my routine. So I figured there might be a conflict with body and range_attack_body due to their SpriteRenderers being part of animations. I added Human.SpriteRenderer to an animation and can still change variables.
I have no clue what is going on, please help. Here is some code:
public class PlayerController2D : PhysicsObject {
public float maxSpeed = 7f;
public float jumpTakeOffSpeed = 7f;
public float posOffset = 1;
protected bool flipSprite = false;
protected bool flipState = true;
private Animator animator;
private SpriteRenderer[] spriteRenderers;
void Awake ()
{
animator = GetComponent<Animator> ();
GameObject human = GameObject.Find("Human");
spriteRenderers = human.GetComponentsInChildren<SpriteRenderer> ();
}
protected override void Attack ()
{
if(Input.GetMouseButton(0))
{
spriteRenderers[0].enabled = false;
spriteRenderers[1].enabled = true;
Debug.LogError("Inhalt:" + spriteRenderers[0].ToString());
Debug.LogError("Inhalt:" + spriteRenderers[1].ToString());
animator.SetBool("attack", true); // boolean to start hold animation
}
else if(!Input.GetMouseButton(0))
{
spriteRenderers[0].enabled = true;
spriteRenderers[1].enabled = false;
animator.SetBool("attack", false);
}
}
}
Your script code is ok, the problem should be elsewhere.
First of all, disable the Animator component and run the script: if enabling/disabling the sprite renderers work, than you must look in the animation clips if you have the Sprite Renderer.Enabled property anywhere, most probably you'll have it - remove it so you can enable/disable the renderers only via script.
If the script still doesn't work, then the problem is elsewhere (another script which is accessing the enabled property of the renderers).
But I'd bet that you're changing the enabled property from the animation clips, which supercedes the script due to how the Unity execution order works (animations are always updated after the scripts and before rendering).

I'm creating an FPS game and I can't work out how to loop the shoot animation of the enemy I've attached the script to until my player dies

The script below is attached to the enemy on my game.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour {
private Animator attack;
Transform player;
UnityEngine.AI.NavMeshAgent nav;
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
nav = GetComponent<UnityEngine.AI.NavMeshAgent> ();
}
The code just below is getting the enemy to stop at a certain distance and shoot from the trigger "Attack". (Below and above are all the same code).
// Update is called once per frame
void Update () {
nav.SetDestination(player.position);
float distance = Vector3.Distance(this.transform.position, player.position);
if (distance < 10f)
{
Animator an = GetComponent<Animator>();
an.SetTrigger("Attack");
}
Debug.Log("distance" + distance);
}
}
This script basically uses the Nav Agent to make the enemy go towards my player and to start a shoot animation when the enemy is at a certain range.
Any help would be great. Thank you.
You should use a boolean for the check instead of a Trigger. You should change your code to set the boolean Attacking to false when the player is not in range and set the boolean to true when the player is in range for attacking. Also, make sure your animation clip loop is ticked on.

Unity: Initializing smoke Prefab via script

I am trying to use a smoke prefab (free asset from Unity asset store). When I add the prefab directly into the game scene, the prefab works:
But when I create the following script to initialize the same prefab (inside a game object), nothing happens:
class Smoke1 : MonoBehaviour
{
public GameObject myPrefab;
void Start()
{
Instantiate(myPrefab, transform.position, transform.rotation);
}
void Update()
{
}
}
My game scene:
Can you help?
Try to use Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);. This will spawn the prefab in the center of the scene. If it works, then it means you're doing something weird with the position and rotation of the object upon instantiation.

Categories

Resources