This is my script:
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Net;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] GameObject Character;
[SerializeField] float moveSpeed;
[SerializeField] float jumpSpeed;
[SerializeField] float xMin;
[SerializeField] float xMax;
[SerializeField] float padding;
[SerializeField] float screenWidthInUnits = 8f;
private Rigidbody2D rigidbody2d;
[SerializeField] bool canJump = true;
[SerializeField] bool playRunAnim;
[SerializeField] bool playJumpAnim;
[SerializeField] bool playIdleAnim;
[SerializeField] Animator animator;
void Start()
{
SetUpMoveBoundaries();
rigidbody2d = GetComponent<Rigidbody2D>();
}
private void SetUpMoveBoundaries()
{
Camera gameCamera = Camera.main;
xMin = gameCamera.ViewportToWorldPoint(new Vector2(0, 0)).x + padding;
xMax = gameCamera.ViewportToWorldPoint(new Vector2(10, 0)).x - padding;
}
void Update()
{
Move();
if (canJump == true)
{
Jump();
}
Animation();
}
private void Move()
{
transform.Translate(Input.GetAxis("Horizontal") * moveSpeed *Time.deltaTime, 0f, 0f);
Vector3 characterScale = transform.localScale;
if (Input.GetAxis("Horizontal") < 0)
{
characterScale.x = -0.33f;
}
if (Input.GetAxis("Horizontal") > 0)
{
characterScale.x = 0.33f;
}
transform.localScale = characterScale;
}
private void Jump()
{
if (Input.GetKeyDown("space"))
{
rigidbody2d.velocity = Vector2.up * jumpSpeed;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Platform"))
{
canJump = true;
playRunAnim = true;
playJumpAnim = false;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Platform"))
{
canJump = false;
playRunAnim = false;
playJumpAnim = true;
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Platform"))
{
canJump = true;
playRunAnim = true;
playJumpAnim = false;
}
}
private void Animation()
{
//run
if (Input.GetKey("d") || Input.GetKey("a"))
{
if (playRunAnim)
{
animator.SetFloat("Speed", 1);
}
else
{
animator.SetFloat("Speed", 0);
}
}
//jump
if (playJumpAnim = true)
{
animator.SetFloat("Jump", 1);
}
else
{
animator.SetFloat("Jump", 0);
}
}
}
The problem is the playJumpVariable won’t change to false from true, so the player gets stuck in a loop of jump script. Does anyone have a solution?