unity animation error resulting in animations not changing by the parameters - c#

I am working in Unity and trying to create an animation controller that changes the direction the player is facing by playing a different animation while a button is pressed.
I keep getting this error "Assets/Maps/Map1/Entities/Player/PlayerMovement.cs(6,18): warning CS0649: Field PlayerMovement.animator' is never assigned to, and will always have its default valuenull'"
This error does not stop the game from playing, but the animation stays in its default position.
This is the code I have as a player controller which is where I alter the parameters for the animation controller. It tells me the error is on line 6 space 18.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
Animator animator;
public float movementSpeed = 100.0f;
public bool Movement = true;
public int Direction = 0;
// Use this for initialization
void Start () {
animator.GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
if (Movement == true) {
if (Input.GetKey (KeyCode.W)) {
transform.Translate ((Vector2.up) * movementSpeed * Time.deltaTime);
animator.SetInteger("Direction",0);
}
if (Input.GetKey (KeyCode.A)) {
transform.Translate ((-Vector2.right) * movementSpeed * Time.deltaTime);
animator.SetInteger("Direction",270);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate ((-Vector2.up) * movementSpeed * Time.deltaTime);
animator.SetInteger("Direction",180);
}
if (Input.GetKey (KeyCode.D)) {
transform.Translate ((Vector2.right) * movementSpeed * Time.deltaTime);
animator.SetInteger("Direction",90);
}
else{
animator.SetInteger("Direction",360);
}
}
}
}
this is an Imgur link to Screen shots of the animator gui for unity. I would have put them directly on this screen, but I don't have the permissions to do that.
Imgur Link

I beleive this is the culprit:
void Start () {
animator.GetComponent<Animator> ();
}
it is not being assinged it should be like this :
void Start ()
{
//you have to use the variable u declared and assing it to the animator
animator = this.GetComponent<Animator> ();
}
hope that solves it.

Related

Animation Starts but player won't move on key press in Unity

Me and 3 friends started working on game and while codding run into error that animation on player starts but it won't move. We are working in Unity(C#)
I already checked for names in Animator and code so it's not it.
Here is a code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float moveSpeed = 5f;
public Animator anim;
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
Jump();
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f , 0f);
transform.position += movement * Time.deltaTime * moveSpeed;
if(Input.GetAxis("Horizontal") > 0){
anim.SetBool("isWalking", true);
}
else
{
anim.SetBool("isWalking", false);
}
}
void Jump(){
if (Input.GetButtonDown("Jump")){
gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f,5f), ForceMode2D.Impulse);
}
}
}
It's 2D game if It matters
You could try to create the rigidbody2d in start(), then try
rigidbody.AddForce(Vector2(moveSpeed,0), ForceMode2D.Impulse);

Animation gets interrupted, but I want the animation to finish

I'm new to coding and I've been playing around with unity and I've encountered a problem.
My problem is, if I move the player and activate the function SkillAttack1, the animation will cancel out and won't complete. Right now, as you see in the code belowif I activate theSkillAttack1`, it works, but still it won't complete the animation. Also, if I'm pressing the "w" button, for example, for 15 seconds the player gets stuck and moves forward. The only way to play the full animation is not moving, but that's not right.
[Animator1][1]
[Animator2][2]
[Animator3][3]
[1]: https://i.stack.imgur.com/BeziY.png
[2]: https://i.stack.imgur.com/310vz.png
[3]: https://i.stack.imgur.com/tOVVu.png
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float velocity = 5;
public float turnSpeed = 10;
Vector2 input;
float angle;
Quaternion targetRotation;
public Transform cam;
public Animator anim;
public bool IsAttacking = false;
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
if(Mathf.Abs(input.x) < 0.5 && Mathf.Abs(input.y) < 0.5) return;
CalculateDirection();
Rotate();
Move();
}
void FixedUpdate()
{
if(IsAttacking == false)
{
GetInput();
}
SkillAttack1();
SkillAttack2();
}
/// Input based on Horizontal(a,d) and Vertical (w,s) keys
void GetInput()
{
input.x = Input.GetAxis("Horizontal");
input.y = Input.GetAxis("Vertical");
anim.SetFloat("VelX", input.x);
anim.SetFloat("VelY", input.y);
}
/// Direction relative to the camera rotation
void CalculateDirection()
{
angle = Mathf.Atan2(input.x, input.y);
angle = Mathf.Rad2Deg * angle;
angle += cam.eulerAngles.y;
}
/// Rotate toward the calculated angle
void Rotate()
{
targetRotation = Quaternion.Euler(0, angle, 0);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, turnSpeed
* Time.deltaTime);
}
/// This player only move along its own forward axis
void Move()
{
transform.position += transform.forward * velocity * Time.deltaTime;
}
public void SkillAttack1(){
if(Input.GetKeyDown("1"))
{
IsAttacking = true;
StartCoroutine(OnSkillAttack1());
}
}
public void SkillAttack2()
{
if(Input.GetKeyDown("2"))
{
anim.SetTrigger("SkillAttack2");
}
}
public IEnumerator OnSkillAttack1()
{
anim.SetTrigger("SkillAttack1");
yield return null;
yield return new WaitForSeconds(15.0f);
IsAttacking = false;
}
}
Looks like your animation controller is getting overridden by your movement code, when your player sends some input to walk left or right, it sets the VelX and VelY variables on your animation controller. Without access to your controller I can't tell you exactly why it's interrupting the attack, but it's likely you have an interrupt set up that triggers from "any state" when one of those variables is above 0 and transitions into the "walk" animation your controller has.
You'll need to adjust your animation transitions to handle this potential case, or alternatively, prevent movement code triggering during an attack animation.

Unity character controller script and animator

Hello so i have this script and in the void update in doesnt matter wich is first for backwards or run up it always makes the animator play the animation backwards walk or run it plays the animation half way or full way and it plays part of the idle state without it been called that means your finger is still in the on the button so it must still play backward/forwards animation over and over .
here is the code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour {
public float moveSpeed = 10f;
public float turnSpeed = 50f;
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
if (Input.GetKey (KeyCode.S)) {
anim.SetBool ("isIdle", false);
anim.SetBool ("isWalkingBack", true);
transform.Translate (-Vector3.forward * moveSpeed * Time.deltaTime);
}
else
{
anim.SetBool ("isIdle", true);
anim.SetBool ("isWalkingBack", false);
}
if (Input.GetKey (KeyCode.W)) {
anim.SetBool ("isRunning", true);
anim.SetBool ("isIdle", false);
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
else
{
anim.SetBool ("isRunning", false);
anim.SetBool ("isIdle", true);
}
}
}
`
Using boolean fields may cause some problems, for example, which you described above.
I recommend to use: anim.SetInteger("unitState", someIntValue);
Configure the connections and transitions in the animator to work with the field "unitState".
In your code it will look something like this:
void Update () {
// for example
anim.SetInteger("unitState", 0); // 0 is Idle
if (Input.GetKey (KeyCode.S)) {
anim.SetInteger("unitState", -1); // -1 is WalkBack
transform.Translate (-Vector3.forward * moveSpeed * Time.deltaTime);
}
if (Input.GetKey (KeyCode.W)) {
anim.SetInteger("unitState", 1); // 1 is run forward
transform.Translate (Vector3.forward * moveSpeed * Time.deltaTime);
}
if (Input.GetKeyDown (KeyCode.Space)) {
anim.SetInteger("unitState", 2); // 2 is jump
//Jump code here. for example
}
....
}
Make sure you have unchecked exit time on every transition.

My object begins to spin when collides with the wall

I have in Unity a box that is followed by a camera on a plane. I'm trying to handle the collisions between the box and different objects. When it collides with different things it spins, jumps and happen weird things. I uploaded to YouTube a video to show the problem. The video.
I created an empty that has the camera and the box. This empty has rigidbody of mass 1.
The empty has a script component:
using UnityEngine;
using System.Collections;
public class Character : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision collision)
{
Debug.Log ("Entered OnCollisionEnter function");
if (collision.gameObject.name == "Wall") {
GetComponent<Rigidbody>().velocity = Vector3.zero;
Debug.Log ("Inside if statement");
}
}
}
As you can see I tried to handle the collision writing a code that stops the cube of moving.
Additional information that could help you guys:
The box
It has a box collider. Script:
using UnityEngine;
using System.Collections;
public class MoveCharacter : MonoBehaviour {
public float deltaMovement = 10f;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
Moving();
}
void Moving()
{
//Moves the character to where it needs.
if (Input.GetKey (KeyCode.A)) {
transform.Translate (new Vector3 (-deltaMovement, 0f, 0f) * Time.deltaTime);
} else if (Input.GetKey (KeyCode.D)){
transform.Translate (new Vector3 (deltaMovement, 0f, 0f) * Time.deltaTime);
}
float yRotation = Camera.main.transform.eulerAngles.y;
float movementX = Mathf.Sin ((yRotation * Mathf.PI) / 180) * deltaMovement;
float movementZ = Mathf.Cos ((yRotation * Mathf.PI) / 180) * deltaMovement;
if (Input.GetKey (KeyCode.W)) {
transform.Translate (new Vector3 (movementX, 0f, movementZ) * Time.deltaTime, Space.World);
} else if (Input.GetKey (KeyCode.S)){
transform.Translate (new Vector3 (-movementX, 0f, -movementZ) * Time.deltaTime, Space.World);
}
}
}
The wall
It is a plane with mesh collider and with or without rigidbody didn't make a difference, same problem...
Any help please?
If you are using physics you shouldn't move an object my changing it's translation, you should move it by applying forces to the object, or at least adding a velocity to it. This will allow the physics engine to correctly calculate the reactions with other rigid bodies.
If you move an object my adjusting it's translation then when a collision occurs it will be as though the object has materialised into the other object to the engine as it will be moving with no velocity etc, and you will get weird behaviour.

Shooting a ball (With gravity)

I am currently having trouble shooting a ball and adding velocity to it. The idea is that the longer you hold down "SPACE" the longer the ball will travel.
What I have so far is this for the player control:
public class PlayerControl : MonoBehaviour {
public float speed = 0f;
Vector3 enVector = new Vector3(10,0,0);
public bool laserDirection = false;
public Transform firePoint;
public GameObject RedBall;
public PlayerControl player;
// Use this for initialization
void Start () { }
// Update is called once per frame
void Update ()
{
// Press CTRL to move the platform under the ball and shoot a laser (NOT FINISHED)
if (Input.GetKey (KeyCode.LeftControl) && laserDirection == false)
{
transform.Translate(enVector * -speed * Time.deltaTime);
}
else if(Input.GetKey (KeyCode.LeftControl) && laserDirection == true)
{
transform.Translate(enVector * speed * Time.deltaTime);
}
// Sets the direction the platform will travel if pressed
if(Input.GetKey (KeyCode.LeftArrow))
{
laserDirection = false;
}
// Sets the direction the platform will travel if pressed
if(Input.GetKey (KeyCode.RightArrow))
{
laserDirection = true;
}
// Shoots a ball the longer you hold down
if(Input.GetKey (KeyCode.Space))
{
GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D> ().velocity.y);
Instantiate(RedBall, firePoint.position, firePoint.rotation);
}
}
// Destroy the ball
void OnTriggerEnter2D(Collider2D other)
{
Destroy (gameObject);
}
}
If you look where the get space button is you see the code I've made for the shooting. This only makes the ball travel to the right at a set speed I've chosen.
This is for changing the direction of the ball (It moves around the big black ball):
// THE DIRECTION OF THE BALL SCRIPT
public class RedBall : MonoBehaviour
{
public Transform target;
void Update()
{
// Moves the ball launcher to the left
if (Input.GetKey (KeyCode.LeftArrow))
{
transform.RotateAround (target.position, transform.forward, Time.deltaTime * 90f);
}
// Moves the ball launcher to the right
if (Input.GetKey (KeyCode.RightArrow))
{
transform.RotateAround (target.position, -transform.forward, Time.deltaTime * 90f);
}
}
}
I am struggling with how to figure out how to make the ball shoot in the direction it is facing, which depends on how it has been translated in the ball script. Additionally, how to make the ball react to the gravity when shot and how to shoot further the longer I hold hold the "SPACE" button.
If anyone knows how to do at least one of these things it would help a lot! Thank you.
(Instead of using Rigidbody2D.velocity try to use Rigidbody2D.AddForce. For turning gravity on and off use Rigidbody2D-gravityScale.
I'm not quite sure what you mean with "the longer I hold the "SPACE button". Do you want to make it a "Spring" and release it when the Space button was released?
edit:
maybe do it like this. make initial force a variable and "Load it" while the button is pressed, when it is release, instantiate the Ball and add the force to it.
i justed typed this out of the head, without testing so maybe it wont run out of the box, but the direction should be clear
if (Input.GetKey(KeyCode.Space))
{
initialForce += 0.1f;
GetComponent<Rigidbody2D>().velocity = new Vector2(speed, GetComponent<Rigidbody2D>().velocity.y);
Instantiate(RedBall, firePoint.position, firePoint.rotation);
}
else
{
if (initialForce > 0)
{
var ball = (GameObject)Instantiate(RedBall, firePoint.position, firePoint.rotation);
ball.GetComponent<Rigidbody2D>.AddForce(firePoint.rotation * Vector2.one * initialForce);
}
initialForce = 0f;
}
So I am struggling with how to figure out how to make the ball shoot
in the direction it is facing depending on how it have been translated
in the ball script.
Multiply speed by the direction you want to shoot in:
// Shoots a ball the longer you hold down
if(Input.GetKey (KeyCode.Space)) {
GetComponent<Rigidbody2D> ().AddForce(transform.forward * speed);
Instantiate(RedBall, firePoint.position, firePoint.rotation);
}
Also look into object pooling, you really shouldnt be instantiating projectiles it takes alot of memory to instantiate and destroy all the time during execution.
Also how to make the ball have the gravity when shot
protected float gravity = 1f;
protected bool isShot = false;
// Update is called once per frame
void Update ()
{
if(isShot)
rigidBody.velocity.z += gravity * Time.deltaTime;
}
shoot longer the longer I hold hold the "SPACE" button.
public float rate = 1.0f;
protected float power = 0f;
// Update is called once per frame
void Update ()
{
if (Input.GetKeyUp (KeyCode.Space))
{
UsePower(power);
power = 0f;
}
if (Input.GetKey (KeyCode.Space))
{
power += rate * Time.deltaTime;
}
}
void UsePower (float _power)
{
// Use power here
}

Categories