Compiler generates "error CS1513: } expected", but } is there - unity3d

I am following a tutorial where I build my first 2D game in Unity.
I added a flipX function to flip my Sprite when I change my direction (pressing A or D)
I tried to use the same script, and tried to compile it there are 2 errors:
Assets\Scripts\Player.cs(83,25): error CS1002: ; expected
Assets\Scripts\Player.cs(83,25): error CS1513: } expected
I know what they mean and checked my script. I'm sure they are there where they are not. I just can't figure out the error.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Rigidbody2D _rigid;
[SerializeField]
private float _jumpForce = 5.0f;
private bool _resetJump = false;
[SerializeField]
private float _speed = 3.5f;
private PlayerAnimation _playerAnim;
private SpriteRenderer _playerSprite;
// Start is called before the first frame update
void Start()
{
_rigid = GetComponent<Rigidbody2D>();
_playerAnim = GetComponent<PlayerAnimation>();
_playerSprite = GetComponentInChildren<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
Movement();
}
void Movement()
{
float horizontalInput = Input.GetAxisRaw("Horizontal");
if (horizontalInput > 0)
{
Flip(true);
}
else if (horizontalInput < 0)
{
Flip(false);
}
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded() == true)
{
Debug.Log("Jump!");
_rigid.velocity = new Vector2(_rigid.velocity.x, _jumpForce);
StartCoroutine(ResetJumpRoutine());
}
_rigid.velocity = new Vector2(horizontalInput * _speed, _rigid.velocity.y);
_playerAnim.Move(horizontalInput);
}
bool IsGrounded()
{
RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, Vector2.down, 0.6f, 1 << 8);
if (hitInfo.collider != null)
{
if (_resetJump == false)
return true;
}
return false;
}
void Flip(bool faceRight)
{
if (faceRight == true)
{
_playerSprite.flipX = false;
}
else if (faceRight == false)
{
_playerSprite,flipX = true;
}
}
IEnumerator ResetJumpRoutine()
{
_resetJump = true;
yield return new WaitForSeconds(0.1f);
_resetJump = false;
}
}

It's a simple mistake, replace _playerSprite,flipX = true; with _playerSprite.flipX = true;.
You have a comma instead of a dot.

Related

after adding animation to the player's code in the play mode, he stopped moving

When creating the game, I came across the problem that after adding animation to the player's code in the play mode, he stopped moving.
I did everything as usual, went into the animator, made an animation, and then set up and added everything necessary to the code in the animator, but after that the player stopped moving although before that everything was fine.
Help me, I hope it's not difficult.
Here is the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[Header("Controlled player")]
public Rigidbody2D rb;
[Header("Tinctures of movement")]
public float PSpeed = 1f;
public float jumpForce = 1f;
[Header("Variable Reduction parameters")]
public float LowingPSPeed;
public float FormedPSpeed;
[Header("Traffic Statuses")]
public bool Move;
public bool Jump;
[Header("")]
[Header("Checking the ground under the player")]
public bool OnGround;
private bool doJump = false;
private bool GOright = false;
private bool GOleft = false;
[Header("Ground Check Settings")]
private float groundRadius = 0.3f;
public Transform groundCheck;
public LayerMask groundMask;
private Animator anim;
void Math()
{
FormedPSpeed = PSpeed / LowingPSPeed;
}
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
Math();
if (Input.GetKeyDown(KeyCode.Space))
{
doJump = true;
}
if (Input.GetKey("d"))
{
GOright = true;
}else
{
GOright = false;
}
if (Input.GetKey("a"))
{
GOleft = true;
}
else
{
GOleft = false;
}
}
void FixedUpdate()
{
OnGround = Physics2D.OverlapCircle(groundCheck.position, groundRadius, groundMask);
if (GOright && Move)
{
transform.position += new Vector3(FormedPSpeed, 0, 0);
GetComponent<SpriteRenderer>().flipX = false;
}
if (GOleft && Move)
{
transform.position += new Vector3(-(FormedPSpeed), 0, 0);
GetComponent<SpriteRenderer>().flipX = true;
}
if (doJump && Jump && OnGround)
{
rb.AddForce(new Vector2(0, (jumpForce * 10)));
anim.SetTrigger("takeOf");
doJump = false;
}
if (OnGround)
{
anim.SetBool("isJump", false);
}else
{
anim.SetBool("isJump", true);
}
if (!GOleft && !GOright)
{
anim.SetBool("isRun", false);
}else
{
anim.SetBool("isRun", true);
}
}
I don't understand why this is happening

In Unity, line of code keeps blocking video in WebGL?

I want to play a video in WebGL but it keeps blocking my video due to one line of code and I don't know why or how to "repair" it. When clicking on play, only one frame is shown and then it stops. (Entire code below).
The issue is this particular line in my Update function:
if (video.isPlaying)
{
if (!video.isPrepared) return;
videoSlider.value = (float)NTime; //This line here!!!
}
If not commented out, the video wont play, for whatever reason.
NTime, which seems to cause the issue, is:
video.time/ ((ulong)(video.frameCount / video.frameRate)) //video is videoPlayer
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Video;
using TMPro;
public class SliderVideo : MonoBehaviour
{
[SerializeField] VideoPlayer video;
[SerializeField] Slider videoSlider;
[SerializeField] Slider volumeSlider;
[SerializeField] Button playButton;
[SerializeField] RawImage fullScreenImage;
[SerializeField] RectTransform buttons;
[SerializeField] Vector3 buttonsPos;
Vector3 buttonsPosCache;
[SerializeField] TextMeshProUGUI buttonLanguage;
[SerializeField] GameObject disableButton;
[SerializeField] GameObject videoRectangle;
int cacheWidth, cacheHeight;
float videoWidth, videoHeight;
float videoWidthCache, videoHeightCache;
double videoTimeCache;
bool fullScreen;
float timerMouse;
public bool languageChange = false;
public string videoFileName;
public string videoFileNameEN;
public string videoFileNameDE;
//Start
private void Start()
{
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[25];
videoRectangle.SetActive(false);
videoHeight = fullScreenImage.gameObject.GetComponent<RectTransform>().sizeDelta.y;
videoWidth = fullScreenImage.gameObject.GetComponent<RectTransform>().sizeDelta.x;
buttonsPosCache = buttons.anchoredPosition;
}
//Update
private void Update()
{
if (video.isPlaying)
{
if (!video.isPrepared) return;
videoSlider.value = (float)NTime;
video.SetDirectAudioVolume(0, volumeSlider.value);
}
if (fullScreen)
{
if (Input.GetAxis("Mouse X") != 0 || Input.GetAxis("Mouse Y") != 0)
{
timerMouse = 0;
buttons.gameObject.SetActive(true);
}
else
{
timerMouse += Time.deltaTime;
if (timerMouse > 3)
{
timerMouse = 3;
buttons.gameObject.SetActive(false);
}
}
}
}
public ulong Duration
{
get { return (ulong)(video.frameCount / video.frameRate); }
}
public double VideoTime
{
get { return video.time; }
}
public double NTime
{
get { return VideoTime / Duration; }
}
//Prepare Method
public void LoadVideo(string source)
{
video.url = System.IO.Path.Combine(Application.streamingAssetsPath, source);
video.Prepare();
}
//Methods for Buttons
public void PlayVideo()
{
//if (!IsPrepared && IsPlaying) return ;
video.Play();
}
public void PauseVideo()
{
if (!video.isPlaying) return;
video.Pause();
}
public void SeekSlider()
{
video.time = (videoSlider.value * Duration);
}
public void PauseResume()
{
//if (!IsPrepared) return ;
videoRectangle.SetActive(true);
if (video.isPlaying)
{
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[25];
PauseVideo();
}
else if (!video.isPlaying)
{
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[24];
PlayVideo();
}
}
public void FullScreen()
{
if (!fullScreen)
{
disableButton.SetActive(false);
fullScreenImage.gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(1920, 1920);
buttons.anchoredPosition = buttonsPos;
fullScreen = true;
}
else
{
disableButton.SetActive(true);
fullScreenImage.gameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(videoWidth, videoHeight);
buttons.anchoredPosition = buttonsPosCache;
fullScreen = false;
}
}
public void ChangeVideoLanguage()
{
if (!languageChange)
{
buttonLanguage.text = "EN";
videoFileName = videoFileNameDE;
video.Stop();
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[25];
LoadVideo(videoFileName);
languageChange = true;
}
else
{
buttonLanguage.text = "DE";
videoFileName = videoFileNameEN;
video.Stop();
playButton.image.sprite = Resources.LoadAll<Sprite>("icons")[25];
LoadVideo(videoFileName);
languageChange = false;
}
}
}

I can't jump and move at the same time unity2d

i made 2d character and 3 ui buttons and they worked well
but the problem is when moving to the right or left by the ui buttons i can't jump however when jump from the ui button i can move to right and left
this is the script
public class PlayerWalk : MonoBehaviour {
private PlayerAnimation playerAnim;
private Rigidbody2D myBody;
private SpriteRenderer spriteRenderer;
public float speed = 7f;
public float jumpForce = 7f;
private bool moveLeft; // determine if we move left or right
private bool dontMove; // determine if we are moving or not
private bool canJump; // we will test if we can jump
void Start () {
playerAnim = GetComponent<PlayerAnimation>();
myBody = GetComponent<Rigidbody2D>();
dontMove = true;
}
void Update () {
//DetectInput();
HandleMoving();
}
void HandleMoving() {
if (dontMove) {
StopMoving();
} else {
if (moveLeft) {
MoveLeft();
} else if (!moveLeft) {
MoveRight();
}
}
} // handle moving
public void AllowMovement(bool movement) {
dontMove = false;
moveLeft = movement;
}
public void DontAllowMovement() {
dontMove = true;
}
public void Jump() {
if(canJump) {
myBody.velocity = new Vector2(myBody.velocity.x, jumpForce);
//myBody.AddForce(Vector2.right * jumpForce);
}
}
// PREVIOUS FUNCTIONS
public void MoveLeft() {
myBody.velocity = new Vector2(-speed, myBody.velocity.y);
playerAnim.ZombieWalk(true, true);
}
public void MoveRight() {
myBody.velocity = new Vector2(speed, myBody.velocity.y);
playerAnim.ZombieWalk(true, false);
}
public void StopMoving() {
playerAnim.ZombieStop();
myBody.velocity = new Vector2(0f, myBody.velocity.y);
}
void DetectInput() {
float x = Input.GetAxisRaw("Horizontal");
if (x > 0)
{
MoveRight();
}
else if (x < 0)
{
MoveLeft();
}
else
{
StopMoving();
}
}
void OnCollisionEnter2D(Collision2D collision) {
if(collision.gameObject.tag == "Ground") {
canJump = true;
}
}
void OnCollisionExit2D(Collision2D collision) {
if (collision.gameObject.tag == "Ground") {
canJump = false;
}
}
} // class
the 2d character moves well and there is no bugs or problems with scripts
Any help??
I don't know where is the problem??
**Note ** i used unity5.6
I would say onTriggerEnter2D instead of using onCollisionEnter2D would be a better option in this scenario. You can read more about that here.
https://answers.unity.com/questions/875770/ontriggerenter-or-oncollisionenter-1.html#:~:text=OnCollisionEnter%20is%20called%20when%20two,with%20%22IsTrigger%22%20set).
Did you try to debug the value of canJump while you are trying to move left or right?

Player want to move left and right from single - touch (Unity)

I made the game in Unity Space Shooter. In my Space shooter there is 2 button it work for Left and Right moving. I want when we touch the left button player go to left only in Single Touch same like Right Button also.
This , are the some codes which i used in Game. Please Help me out from this.
TouchControl.cs
using UnityEngine;
using System.Collections;
public class TouchControl : MonoBehaviour {
public GUITexture moveLeft;
public GUITexture moveRight;
public GUITexture fire;
public GameObject player;
private PlayerMovement playerMove;
private Weapon[] weapons;
void Start()
{
playerMove = player.GetComponent<PlayerMovement> ();
}
void CallFire()
{
weapons = player.GetComponentsInChildren<Weapon> ();
foreach (Weapon weapon in weapons) {
if(weapon.enabled == true)
weapon.Fire();
}
}
void Update()
{
// int i = 0;
if(Input.touchCount > 0)
{
for(int i =0; i < Input.touchCount; i++)
{
// if(moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// playerMove.MoveLeft();
// }
// }
// if(moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// playerMove.MoveRight();
// }
// }
// if(moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
// {
// if(Input.touchCount > 0)
// {
// CallFire();
// }
// }
// Touch t = Input.GetTouch(i);
Touch t = Input.GetTouch (i);
Input.multiTouchEnabled = true;
if(t.phase == TouchPhase.Began || t.phase == TouchPhase.Stationary)
{
if(moveLeft.HitTest(t.position, Camera.main))
{
playerMove.MoveLeft ();
}
if(moveRight.HitTest(t.position, Camera.main))
{
playerMove.MoveRight();
}
}
if(t.phase == TouchPhase.Began)
{
if(fire.HitTest(t.position, Camera.main))
{
CallFire();
}
}
if(t.phase == TouchPhase.Ended)
{
}
}
}
}
}
PlayerMovement.cs
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
public float speedMove = 6.0f;
public float bonusTime;
private bool toLeft = false;
private bool toRight = false;
public GameObject shield;
public GUIText bonustimeText;
private bool counting = false;
private float counter;
private Weapon[] addWeapons;
public Sprite strongShip;
public Sprite normalSprite;
public Sprite shieldSprite;
private SpriteRenderer sRender;
private Weapon weaponScript;
void Start () {
counter = bonusTime;
sRender = GetComponent<SpriteRenderer> ();
addWeapons = GetComponentsInChildren<Weapon> ();
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = false;
}
weaponScript = GetComponent<Weapon>();
weaponScript.enabled = true;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.A)) {
toLeft = true;
}
if (Input.GetKeyUp (KeyCode.A)) {
toLeft = false;
}
if (Input.GetKeyDown (KeyCode.D)) {
toRight = true;
}
if (Input.GetKeyUp (KeyCode.D)) {
toRight = false;
}
if (counting) {
counter -= Time.deltaTime;
bonustimeText.text = counter.ToString("#0.0");
}
}
void FixedUpdate()
{
if (toLeft) {
MoveLeft();
}
if (toRight) {
MoveRight();
}
}
public void MoveLeft()
{
transform.Translate(Vector2.right * -speedMove* Time.deltaTime);
}
public void MoveRight()
{
transform.Translate(Vector2.right * speedMove * Time.deltaTime);
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "StrongMode") {
Destroy (coll.gameObject);
counting = true;
StrongMode();
Invoke ("Downgrade", bonusTime);
}
if (coll.gameObject.tag == "ShieldMode") {
Destroy (coll.gameObject);
counting = true;
ShieldMode();
Invoke("Downgrade", bonusTime);
}
if (coll.gameObject.tag == "Life") {
GUIHealth gui = GameObject.Find ("GUI").GetComponent<GUIHealth> ();
gui.AddHealth();
SendMessage("AddHp");
SoundHelper.instanceSound.PickUpSound();
Destroy(coll.gameObject);
}
if (coll.gameObject.tag == "Enemy") {
SendMessage("Dead");
}
}
void Downgrade()
{
SoundHelper.instanceSound.BonusDownSound ();
counting = false;
bonustimeText.text = "";
counter = bonusTime;
sRender.sprite = normalSprite;
weaponScript.enabled = true;
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = false;
}
weaponScript.enabled = true;
shield.SetActive (false);
}
void StrongMode()
{
SoundHelper.instanceSound.BonusUpSound ();
sRender.sprite = strongShip;
foreach (Weapon addWeapon in addWeapons) {
addWeapon.enabled = true;
}
weaponScript.enabled = false;
}
void ShieldMode()
{
SoundHelper.instanceSound.BonusUpSound ();
sRender.sprite = shieldSprite;
shield.SetActive (true);
}
// void OnDestroy()
// {
// bonustimeText.text = "";
// }
}
In the Player Controller script Create:
public Vector3 playerDirection = Vector3.zero;
Then in touch control instead of:
if (moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.MoveLeft();
}
}
if (moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.MoveRight();
}
}
Use:
if (moveLeft.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.playerDirection = Vector3.left;
}
}
if (moveRight.HitTest(Input.GetTouch(i).position, Camera.main))
{
if (Input.touchCount > 0)
{
playerMove.playerDirection = Vector3.right;
}
}
Then in the Update method of Player Controller use:
transform.Translate(playerDirection * speedMove * Time.deltaTime);
public class PlayerController {
public EPlayerState playerState = EPLayerState.Idle;
void Update () {
// If click right button
playerState = EPlayerState.MoveRight;
// Else if click left button
playerState = EPlayerState.MoveLeft
if (playerState == EPlayerState.MoveRight)
// Move player right;
if (playerState == EPlayerState.MoveLeft
// Move player right;
}
}
public enum EPlayerState {
Idle,
MoveRight,
MoveLeft
}
You can also use something like a boolean called isRight, move right when it's true and left when it's false. Then when you click left or right button just change the variable.
`using UnityEngine;
public class HalfScreenTouchMovement : MonoBehaviour
{
private float screenCenterX;
private void Start()
{
// save the horizontal center of the screen
screenCenterX = Screen.width * 0.5f;
}
private void Update()
{
// if there are any touches currently
if(Input.touchCount > 0)
{
// get the first one
Touch firstTouch = Input.GetTouch(0);
// if it began this frame
if(firstTouch.phase == TouchPhase.Began)
{
if(firstTouch.position.x > screenCenterX)
{
// if the touch position is to the right of center
// move right
}
else if(firstTouch.position.x < screenCenterX)
{
// if the touch position is to the left of center
// move left
}
}
}
}
}`
May be helpfull
create script. for example player.cs
public class PlayerController : MonoBehaviour
{
bool swipeRight = false;
bool swipeLeft = false;
bool touchBlock = true;
bool canTouchRight = true;
bool canTouchLeft = true;
void Update()
{
swipeLeft = Input.GetKeyDown("a") || Input.GetKeyDown(KeyCode.LeftArrow);
swipeRight = Input.GetKeyDown("d") || Input.GetKeyDown(KeyCode.RightArrow);
TouchControl();
if(swipeRight) //rightMove logic
else if(swipeLeft) //leftMove logic
}
void TouchControl()
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved && touchBlock == true)
{
touchBlock = false;
// Get movement of the finger since last frame
var touchDeltaPosition = Input.GetTouch(0).deltaPosition;
Debug.Log("touchDeltaPosition "+touchDeltaPosition);
if(touchDeltaPosition.x > 0 && canTouchRight == true)
{
//rightMove
swipeRight = true; canTouchRight = false;
Invoke("DisableSwipeRight",0.2f);
}
else if(touchDeltaPosition.x < 0 && canTouchLeft == true)
{
//leftMove
swipeLeft = true; canTouchLeft = false;
Invoke("DisableSwipeLeft",0.2f);
}
}
}
void DisableSwipeLeft()
{
swipeLeft = false;
touchBlock = true;
canTouchLeft = true;
}
void DisableSwipeRight()
{
swipeRight = false;
touchBlock = true;
canTouchRight = true;
}
}

Unity 2D - HP bar

The value of my HP bar drops when my runner collides an obstacle. Of course, Value of HP drop nomally, but Image of HP bar does not change. Why do I get an error?
public class CsRunner : MonoBehaviour
{
public Vector2 jumpVelocity;
public float _hp = 100f;
public float _curHP;
bool isJump;
public Image _hpValue;
bool collision_box;
// Use this for initialization
void Start()
{
_hpValue = GameObject.Find("HPbar").GetComponent<Image>();
_curHP = _hp;
}
// Update is called once per frame
void Update()
{
_hpValue.fillAmount = _curHP / _hp;
if (Input.GetKeyDown(KeyCode.Space) && isJump)
{
isJump = false;
transform.GetComponent<Rigidbody2D>().AddForce(jumpVelocity/2, ForceMode2D.Impulse);
}
if ((Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0)) && collision_box)
{
isJump = true;
transform.GetComponent<Rigidbody2D>().AddForce(jumpVelocity, ForceMode2D.Impulse);
}
else
{
GetComponent<Animator>().SetTrigger("Run");
}
}
void OnTriggerEnter2D(Collider2D coll)
{
if (coll.transform.tag == "Enemy")
{
_curHP--;
_hpValue.fillAmount = _curHP / _hp;
}
}
}
Here is a screenshot of my scene :
Thank you !