I get Unity error "cannot access componet because of accessibility" - c#

Here is my C# code:
using UnityEngine;
using UnityEngine.AI;
public class ShootingAi : MonoBehaviour
{
public NavMeshAgent agent;
public Animator animator;
public CharacterController cc;
public Transform player, wallCheck;
public GameObject gun;
//Movement && Stats
public int health;
public float walkSpeed, runSpeed, gravityMultiplier;
//Check for Ground/Obstacles
public LayerMask whatIsGround, whatIsPlayer,whatIsObject,whatIsAll;
//Patroling
public Vector3 walkPoint;
public Vector2 distanceToWalkPoint;
public bool walkPointSet;
public float walkPointRange;
//Attack Player
public float timeBetweenAttacks;
bool alreadyShot;
//State machine
public bool isPatroling, isChasing, isAttacking, isDead;
public float sightRange, attackRange;
public bool grounded, playerInSightRange, playerInAttackRange, blockingObject;
//Stupid gunAnimFix :D
public GameObject walkPointGraphic;
public GameObject gunRunning, gunWalking, gunShooting;
private void Awake()
{
player = GameObject.Find("PlayerObj").transform;
}
private void Update()
{
StateMachine();
Movement();
AnimationController();
//SetWalkPoint
//if (walkPointGraphic != null)
//walkPointGraphic.transform.position = new Vector3(walkPoint.x, 1.738182f, walkPoint.z);
}
private void AnimationController()
{
if (isPatroling) animator.SetBool("walking", true);
else animator.SetBool("walking", false);
if (isAttacking) animator.SetBool("shooting", true);
else animator.SetBool("shooting", false);
if (isChasing) animator.SetBool("running", true);
else animator.SetBool("running", false);
if (isDead) animator.SetBool("dead", true);
else animator.SetBool("dead", false);
//Don't copy to other projects...
if (isPatroling) gunWalking.SetActive(true);
else gunWalking.SetActive(false);
if (isAttacking) gunShooting.SetActive(true);
else gunWalking.SetActive(false);
if (isChasing) gunRunning.SetActive(true);
else gunRunning.SetActive(false);
}
private void Movement()
{
//extra gravity
cc.Move(-transform.up * Time.deltaTime * gravityMultiplier);
}
private void StateMachine()
{
if (!isDead){
//Check if Player in sightrange
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
//Check if Player in attackrange
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if ((!playerInSightRange && !playerInAttackRange)|| blockingObject) Patroling();
if (playerInSightRange && !playerInAttackRange && !blockingObject) ChasePlayer();
if (playerInAttackRange && playerInSightRange && !blockingObject) AttackPlayer();
}
}
private void Patroling()
{
if (isDead) return;
isPatroling = true;
isChasing = false;
isAttacking = false;
//Calculates DistanceToWalkPoint
distanceToWalkPoint = new Vector2(Mathf.Abs(walkPoint.x) - Mathf.Abs(transform.position.x), Mathf.Abs(walkPoint.z) - Mathf.Abs(transform.position.z));
if (!walkPointSet) SearchWalkPoint();
//Calculate direction and walk to Point
if (walkPointSet){
agent.SetDestination(walkPoint);
Vector3 direction = walkPoint - transform.position;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), 0.15f);
}
//Walkpoint reached
if (distanceToWalkPoint.x < 1f && distanceToWalkPoint.y < 1f)
walkPointSet = false;
}
private void SearchWalkPoint()
{
if (isDead) return;
float randomZ = Random.Range(-walkPointRange, walkPointRange);
float randomX = Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
if (Physics.Raycast(walkPoint,-transform.up, 2,whatIsGround))
walkPointSet = true;
}
private void ChasePlayer()
{
if (isDead) return;
isPatroling = false;
isChasing = true;
isAttacking = false;
//Direction Calculate && move
agent.SetDestination(player.position);
Vector3 direction = player.position - transform.position;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), 0.15f);
}
private void AttackPlayer()
{
if (isDead) return;
isPatroling = false;
isChasing = false;
isAttacking = true;
transform.LookAt(new Vector3(player.position.x,player.position.y, player.position.z));
if (!alreadyShot){
gun.GetComponent<Gun>().Shoot();
alreadyShot = true;
Invoke("ResetShot", timeBetweenAttacks);
}
}
private void ResetShot()
{
if (isDead) return;
alreadyShot = false;
}
public void TakeDamage(int damage)
{
health -= damage;
if (health < 0){
isDead = true;
isAttacking = false;
isChasing = false;
isPatroling = false;
Invoke("Destroyy", 2.8f);
}
}
private void Destroyy()
{
Destroy(gameObject);
}
}
And I get this error:
Severity Code Description Project File Line Suppression State
Error CS0122 'Gun.Shoot()' is inaccessible due to its protection level Assembly-CSharp C:\Users\staff\Downloads\EnemyAi (Project file) woLibrary\Assets\Stuff\EnemyChar\ShootingAi.cs 156 Active
I am running on unity version 2020.3.12f1
And my gun.shoot() script is:
public void Shoot()
{
readyToShoot = false;
//RayCast
if (Physics.Raycast(transform.position, enemy.forward, out rayHit, range, whatIsPlayer))
{
if (rayHit.collider.gameObject.GetComponent<playerMovement>())
//rayHit.collider.GetComponent<playerMovement>().TakeDamage(damage);
Debug.Log(rayHit.collider.gameObject.name);
}
bulletsLeft--;
Instantiate(muzzleFlash, attackPos.position, Quaternion.identity);
Invoke("ShotReset", timeBetweenShooting);
}

Related

I'm trying to assign a float to velocityZ, velocityX but it doesnt work. it stays at 0

So I have to script that assigns moveDirection to a velocityX, and velocityY. I also have the second script that accesses it. I;m doing all this to create a 8 direction animation in unity.
So here's the code
private void ApplyFinalMovements()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
currentInput = new Vector2(_speed * verticalInput, _speed * horizontalInput);
#region CheckingInputsAnims
if (verticalInput>0)
isWalking = true;
else isWalking = false;
if (verticalInput<0)
isWalkingBackwards = true;
else isWalkingBackwards = false;
#endregion
float moveDirectionY = moveDirection.y;
moveDirection = transform.transform.TransformDirection(Vector3.forward * currentInput.x) + (transform.TransformDirection(Vector3.right) * currentInput.y);
velocityZ = moveDirection.y;
velocityX = moveDirection.x;
moveDirection.y = moveDirectionY;
}
And the script that accesses the velocity in order to get it into animator
public class animationStateController : MonoBehaviour
{
Player player;
Animator animator;
private float velocityZ;
private float velocityX;
private void Start()
{
player = FindObjectOfType(typeof(Player)) as Player;
animator = GetComponent<Animator>();
}
void Update()
{
player.velocityZ = velocityZ;
player.velocityX = velocityX;
animator.SetFloat("VelocityZ", velocityZ, 0.1f, Time.deltaTime);
animator.SetFloat("VelocityX", velocityX, 0.1f, Time.deltaTime);
if (player.isWalking)
animator.SetBool("isWalking", true);
else animator.SetBool("isWalking", false);
if (player.isWalkingBackwards)
animator.SetBool("isWalkingBackwards", true);
else animator.SetBool("isWalkingBackwards", false);
if (player.isSprinting)
animator.SetBool("isSprinting", true);
else animator.SetBool("isSprinting", false);
if (player.startJump)
animator.SetBool("startJump", true);
else animator.SetBool("startJump", false);
if (player.midAir)
animator.SetBool("midAir", true);
else animator.SetBool("midAir", false);
if (player.endJump)
animator.SetBool("endJump", true);
else animator.SetBool("endJump", false);
if (player.isCrouching)
animator.SetBool("isCrouching", true);
else animator.SetBool("isCrouching", false);
}
}
Here's the whole code for Player:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine;
public class Player : MonoBehaviour
{
private CharacterController _controller;
private Camera playerCamera;
[Header("Stats")]
[Header("Functional Optons")]
[SerializeField] private bool canLook = true;
[SerializeField] private bool canMove = true;
[SerializeField] private bool canSprint = true;
[SerializeField] private bool canJump = true;
[SerializeField] private bool canCrouch = true;
[SerializeField] private bool WillSlideOnSlopes = true;
[SerializeField] private bool canUseHeadbob = true;
[SerializeField] private bool useFootsteps = true;
[SerializeField] private bool canInteract = true;
[SerializeField] private bool UseStamina = true;
public bool midAir;
private bool midAirLastFrame = false;
[Header("Animator Parameters")]
public float velocityZ;
public float velocityX;
[Header("Controls")]
public KeyCode sprintKey = KeyCode.LeftShift;
public KeyCode jumpKey = KeyCode.Space;
public KeyCode crouchKeyHold = KeyCode.LeftControl;
public KeyCode crouchKeySwitch = KeyCode.C;
public KeyCode interactKey = KeyCode.E;
[Header("Movement Parameters")]
[SerializeField] private float _speed = 3f;
[SerializeField] private float _sprintSpeed = 5f;
[SerializeField] private float _crouchSpeed = 2f;
[SerializeField] private float _slideSpeed = 12f;
public bool isWalking;
public bool isWalkingBackwards;
public bool isSprinting;
private bool SlidedLastFrame;
private Vector3 moveDirection;
private Vector2 currentInput;
[Header("Jumping Parameters")] // dźwięk spadania dodać po czasie się zwiększa
[SerializeField] private float _gravity = 9.81f;
[SerializeField] private float _jumpHeight = 3f;
[SerializeField] private float _fallSpeed;
[SerializeField] private float _fallDamage;
private float _landStartPos;
[SerializeField] private AudioClip[] jumpClips = default;
[SerializeField] private AudioClip[] landClips = default;
public bool startJump;
public bool endJump;
[Header("Crouching Parameters")]
[SerializeField] private float crouchHeight = 1f;
[SerializeField] private float standingHeight = 2.25f;
[SerializeField] private float timeToCrouch = 0.25f;
[SerializeField] private Vector3 crouchingCenter = new Vector3(0, 0f, 0);
[SerializeField] private Vector3 standingCenter = new Vector3(0, 0, 0);
public bool isCrouching;
private bool duringCrouchAnim;
[Header("Look Parameters")]
public float _sensitivity = 100f;
float xRotation = 0f;
private bool cursorShow = false;
[Header("Health Parameters")]
[SerializeField] private float maxHealth = 100f;
[SerializeField] private float timeBeforeRegenStarts = 8f;
[SerializeField] private float healthValueIncrement = 0.5f;
[SerializeField] private float healthTimeIncrement = 0.1f;
[SerializeField] private AudioClip[] hurtClips = default; //SZUKASZ AUDIO SOURCE ZYCIE
[SerializeField] private AudioSource playerAudioSource = default;
[SerializeField] private float currentHealth;
private Coroutine regeneratingHealth; //ogarnij couritine
public static Action<float> OnTakeDamage;
public static Action<float> OnDamage;
public static Action<float> OnHeal;
[Header("Stamina Parameters")]
[SerializeField] private float maxStamina = 100f;
[SerializeField] private float staminaUseMultiplier = 6f;
[SerializeField] private float timeBeforeStaminaRegen = 4.5f;
[SerializeField] private float staminaValueIncrement = 1.5f;
[SerializeField] private float staminaTimeIncrement = 0.1f;
[SerializeField] private float currentStamina;
private Coroutine regeneratingStamina;
public static Action<float> OnStaminaChange;
[Header("Headbob Parameters")]
private float walkBobSpeed = 14.65f;
private float walkBobAmount = 0.03f;
private float sprintBobSpeed = 20f;
private float sprintBobAmount = 0.06f;
private float crouchBobSpeed = 9.75f;
private float crouchBobAmount = 0.04f;
private float defaultYPos = 0;
private float timer;
[Header("Footstep Parameters")]
[SerializeField] private float baseStepSpeed = 0.5f;
[SerializeField] private float crouchStepMultiplier = 1.4f;
[SerializeField] private float sprintStepMultiplier = 0.6f;
[SerializeField] private AudioSource footstepAudioSource = default;
[SerializeField] private AudioClip[] woodClips = default;
[SerializeField] private AudioClip[] stoneClips = default;
[SerializeField] private AudioClip[] grassClips = default;
private float footstepTimer = 0;
private float GetCurrentOffset => isCrouching ? baseStepSpeed * crouchStepMultiplier : isSprinting ? baseStepSpeed * sprintStepMultiplier : baseStepSpeed; // ogarnij to i zaimplementuj do całego kodu
[Header("Sliding Parameters")]
private Vector3 hitPointNormal;
private bool IsSliding
{
get //dodaj to że po zakończeniu slide'a dalej cie wypycha w kierunek w który wcześniej zjeżdżałeś, abyś nie kończył na końcu.
{
if (_controller.isGrounded && Physics.Raycast(transform.position, Vector3.down, out RaycastHit slopeHit, 1.8f))
{
hitPointNormal = slopeHit.normal;
return Vector3.Angle(hitPointNormal, Vector3.up) > _controller.slopeLimit;
}
else
{
return false;
}
}
} // dodaj dźwięk ślizgania się
[Header("Interaction")]
[SerializeField] private Vector3 interactionRayPoint = default;
[SerializeField] private float interactionDistance = default;
[SerializeField] private LayerMask interactionLayer = default;
private Interactable currentInteractable;
private void OnEnable()
{
OnTakeDamage += ApplyDamage;
}
private void OnDisable()
{
OnTakeDamage -= ApplyDamage;
}
void Awake()
{
_controller = GetComponent<CharacterController>();
playerCamera = GetComponentInChildren<Camera>();
defaultYPos = playerCamera.transform.localPosition.y;
currentHealth = maxHealth;
currentStamina = maxStamina;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
Screen.SetResolution(1920, 1080, true);
}
void Update() // ogarnij machanie mieczem i niszczenie skrzynek
{
_speed = 3f;
isSprinting = false;
if (canLook)
MouseLook();
if (canSprint)
Sprinting();
if (canJump)
Jumping();
if (canCrouch)
Crouching();
if (canUseHeadbob)
HandleHeadbob();
if (useFootsteps)
HandleFootsteps();
if (canInteract)
{
HandleInteractionCheck();
HandleInteractionInput();
}
if (UseStamina)
HandleStamina();
if (Input.GetKeyDown(KeyCode.Tab) && cursorShow)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
cursorShow = false;
canLook = true;
}
else if(Input.GetKeyDown(KeyCode.Tab) && !cursorShow)
{
Cursor.lockState = CursorLockMode.Confined;
Cursor.visible = true;
cursorShow = true;
canLook = false;
}
if (canMove)
ApplyFinalMovements();
if (WillSlideOnSlopes && IsSliding)
{
moveDirection += new Vector3(hitPointNormal.x, -hitPointNormal.y, hitPointNormal.z) * _slideSpeed;
SlidedLastFrame = true;
}
_controller.Move(moveDirection * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
private void ApplyFinalMovements()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
currentInput = new Vector2(_speed * verticalInput, _speed * horizontalInput);
#region CheckingInputsAnims
if (verticalInput>0)
isWalking = true;
else isWalking = false;
if (verticalInput<0)
isWalkingBackwards = true;
else isWalkingBackwards = false;
#endregion
float moveDirectionY = moveDirection.y;
moveDirection = transform.transform.TransformDirection(Vector3.forward * currentInput.x) + (transform.TransformDirection(Vector3.right) * currentInput.y);
velocityZ = moveDirection.y;
velocityX = moveDirection.x;
moveDirection.y = moveDirectionY;
}
private void MouseLook()
{
float mouseX = Input.GetAxis("Mouse X") * _sensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * _sensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90, 90);
playerCamera.transform.localRotation = Quaternion.Euler(xRotation, 0, 0);
transform.Rotate(Vector3.up * mouseX);
}
private void Sprinting()
{
if (Input.GetKey(sprintKey) && Input.GetAxis("Vertical") > 0 && !IsSliding && !isCrouching && canSprint)
{
isSprinting = true;
_speed = _sprintSpeed;
}
}
private void Jumping() // dodaj dźwięk spadania przy wysokich prędkościach, którego głośność się będzie zwiększała
{
startJump = false;
if (SlidedLastFrame && !IsSliding)
{
moveDirection.y = -1f;
SlidedLastFrame = false;
}
_fallSpeed = moveDirection.y;
if (midAir)
midAirLastFrame = true;
if (_controller.isGrounded)
midAir = false;
if (_controller.isGrounded && Input.GetKeyDown(jumpKey) && !IsSliding && canJump)
{
startJump = true;
playerAudioSource.PlayOneShot(jumpClips[UnityEngine.Random.Range(0, landClips.Length - 1)]);
moveDirection.y = _jumpHeight;
midAir = true;
}
else if (_controller.isGrounded)
{
if(midAirLastFrame)
endJump = true;
if (midAirLastFrame && !IsSliding && _fallSpeed < -3.5f) // ogarnijjj toooo
{
midAirLastFrame = false;
_landStartPos = playerCamera.transform.localPosition.y;
if (_fallSpeed <= -3.5f)
{
playerAudioSource.PlayOneShot(landClips[UnityEngine.Random.Range(0, landClips.Length - 1)]);
if (_fallSpeed <= -8f) _fallDamage = -moveDirection.y * 1.7f;
if (_fallSpeed <= -9f) _fallDamage *= 2f;
if (_fallSpeed <= -10f) _fallDamage *= 1.5f;
if (_fallSpeed <= -11f) _fallDamage *= 1.5f;
if (_fallSpeed <= -8f) {
Player.OnTakeDamage(_fallDamage);
Debug.Log("Took fallDamage = " + _fallDamage + "with fallspeed = " + _fallSpeed);
}
_fallDamage = 0f;
}
}
moveDirection.y = -1f;
}
else
{
midAir = true;
moveDirection.y -= _gravity * Time.deltaTime;
if (Physics.Raycast(playerCamera.transform.position, Vector3.up, 0.5f) && moveDirection.y > 0f)
{
moveDirection.y = 0f;
}
}
}
private void Crouching()
{
if (Input.GetKeyDown(crouchKeyHold) && !duringCrouchAnim && _controller.isGrounded)
{
StartCoroutine(CrouchStand());
}
else if (isCrouching)
{
_speed = _crouchSpeed;
}
}
private void HandleHeadbob()
{
if (!_controller.isGrounded)
{
return;
}
if (Mathf.Abs(moveDirection.x) > 0.1f || Mathf.Abs(moveDirection.z) > 0.1f)
{
timer += Time.deltaTime * (isCrouching ? crouchBobSpeed : isSprinting ? sprintBobSpeed : walkBobSpeed);
playerCamera.transform.localPosition = new Vector3(
playerCamera.transform.localPosition.x,
defaultYPos + Mathf.Sin(timer) * (isCrouching ? crouchBobAmount : isSprinting ? sprintBobAmount : walkBobAmount),
playerCamera.transform.localPosition.z);
}
}
private void HandleStamina()
{
if (isSprinting && currentInput != Vector2.zero)
{
if (regeneratingStamina != null)
{
StopCoroutine(regeneratingStamina);
regeneratingStamina = null;
}
currentStamina -= staminaUseMultiplier * Time.deltaTime;
if (currentStamina < 0)
{
currentStamina = 0;
}
OnStaminaChange?.Invoke(currentStamina);
if (currentStamina <= 0)
{
canSprint = false;
}
}
if (!isSprinting && currentStamina < maxStamina && regeneratingStamina == null)
{
regeneratingStamina = StartCoroutine(RegenerateStamina());
}
}
private void HandleFootsteps()
{
if (!_controller.isGrounded) return;
if (currentInput == Vector2.zero) return;
footstepTimer -= Time.deltaTime;
if (footstepTimer <= 0)
{
if (Physics.Raycast(playerCamera.transform.position, Vector3.down, out RaycastHit hit, 3))
{
switch (hit.collider.tag)
{
case "Footsteps/STONE":
footstepAudioSource.PlayOneShot(stoneClips[UnityEngine.Random.Range(0, stoneClips.Length - 1)]);
break;
default:
footstepAudioSource.PlayOneShot(stoneClips[UnityEngine.Random.Range(0, stoneClips.Length - 1)]);
break;
}
}
footstepTimer = GetCurrentOffset;
}
}
private void ApplyDamage(float dmg) //ogarnij te float
{
currentHealth -= dmg;
playerAudioSource.PlayOneShot(hurtClips[UnityEngine.Random.Range(0, landClips.Length - 1)]);
OnDamage?.Invoke(currentHealth);
if (currentHealth <= 0)
{
KillPlayer();
}
else if (regeneratingHealth != null)
{
StopCoroutine(regeneratingHealth);
}
regeneratingHealth = StartCoroutine(RegenerateHealth());
}
private void KillPlayer()
{
currentHealth = 0;
if (regeneratingHealth != null)
{
StopCoroutine(regeneratingHealth);
Debug.Log("DEAD");
}
}
private void HandleInteractionCheck()
{
if (Physics.Raycast(playerCamera.ViewportPointToRay(interactionRayPoint), out RaycastHit hit, interactionDistance))
{
if (hit.collider.gameObject.layer == 8 && (currentInteractable == null || hit.collider.gameObject.GetInstanceID() != currentInteractable.GetInstanceID()))
{
hit.collider.TryGetComponent(out currentInteractable);
if (currentInteractable)
{
currentInteractable.OnFocus();
}
}
else if (currentInteractable)
{
currentInteractable.OnLoseFocus();
currentInteractable = null;
}
}
else if (currentInteractable)
{
currentInteractable.OnLoseFocus();
currentInteractable = null;
}
}
private void HandleInteractionInput()
{
if (Input.GetKeyDown(interactKey) && currentInteractable != null && Physics.Raycast(playerCamera.ViewportPointToRay(interactionRayPoint), out RaycastHit hit, interactionDistance, interactionLayer))
{
currentInteractable.OnInteract();
}
}
private IEnumerator CrouchStand()
{
if (isCrouching && Physics.Raycast(playerCamera.transform.position, Vector3.up, 0.5f))
{
yield break;
}
duringCrouchAnim = true;
float timeElapsed = 0;
float targetHeight = isCrouching ? standingHeight : crouchHeight;
float currentHeight = _controller.height;
Vector3 targetCenter = isCrouching ? standingCenter : crouchingCenter;
Vector3 currentCenter = _controller.center;
while (timeElapsed < timeToCrouch)
{
_controller.height = Mathf.Lerp(currentHeight, targetHeight, timeElapsed / timeToCrouch);
_controller.center = Vector3.Lerp(currentCenter, targetCenter, timeElapsed / timeToCrouch);
timeElapsed += Time.deltaTime;
yield return null;
}
_controller.height = targetHeight;
_controller.center = targetCenter;
isCrouching = !isCrouching;
duringCrouchAnim = false;
}
private IEnumerator RegenerateHealth()
{
yield return new WaitForSeconds(timeBeforeRegenStarts);
WaitForSeconds timeToWait = new WaitForSeconds(healthTimeIncrement);
while (currentHealth < maxHealth)
{
currentHealth += healthValueIncrement;
if (currentHealth > maxHealth)
{
currentHealth = maxHealth;
}
OnHeal?.Invoke(currentHealth);
yield return timeToWait;
}
regeneratingHealth = null;
}
private IEnumerator RegenerateStamina()
{
yield return new WaitForSeconds(timeBeforeStaminaRegen);
WaitForSeconds timeToWait = new WaitForSeconds(staminaTimeIncrement);
while (currentStamina < maxStamina)
{
if (currentStamina > 0)
{
canSprint = true;
}
currentStamina += staminaValueIncrement;
if (currentStamina > maxStamina)
{
currentStamina = maxStamina;
}
OnStaminaChange?.Invoke(currentStamina);
yield return timeToWait;
}
regeneratingStamina = null;
}
}
First consider using an enum rather than multiple if...else statements for your current state.
Then, after reviewing the full code, i'm pretty sure the issue come from the fact that your not correctly assigning your values.
Try reverting player.velocityZ = velocityZ; to velocityZ = player.velocityZ; that should do the trick.
That might be it if i understand correctly.
public enum State
{
isWalking,
isWalkingBackwards,
isSprinting,
startJump,
midAir,
endJump,
isCrouching,
}
public class animationStateController : MonoBehaviour
{
Player player;
Animator animator;
private float velocityZ;
private float velocityX;
State lastAnim;
State currentAnim;
private void Start()
{
player = FindObjectOfType(typeof(Player)) as Player;
animator = GetComponent<Animator>();
}
void Update()
{
velocityZ = player.velocityZ;
velocityX = player.velocityX;
animator.SetFloat("VelocityZ", velocityZ, 0.1f, Time.deltaTime);
animator.SetFloat("VelocityX", velocityX, 0.1f, Time.deltaTime);
if (lastAnim != currentAnim)
{
animator.SetBool(currentAnim.ToString(), true)
animator.SetBool(lastAnim.ToString(), false);
}
lastAnim = currentAnim;
}
private void ApplyFinalMovements()
{
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
currentInput = new Vector2(_speed * verticalInput, _speed * horizontalInput);
#region CheckingInputsAnims
if (verticalInput > 0)
currentAnim = State.isWalking;
else if (verticalInput < 0)
currentAnim = State.isWalkingBackwards;
#endregion
float moveDirectionY = moveDirection.y;
moveDirection = transform.transform.TransformDirection(Vector3.forward * currentInput.x) + (transform.TransformDirection(Vector3.right) * currentInput.y);
velocityZ = moveDirection.y;
velocityX = moveDirection.x;
}
}

Unity2D-How to restore hearts after destroying them when Player gets hit

I am using Destroy(Corazones[0].gameObject); to destroy 5 hearts in an array, but I need to restore them when the player gets another heart. I already have the collider that increases lives +1 and it works, but I do not know how to respawn the heart that represents that life.
The hearts get destroyed when the player gets Hit(); but I also need for the hearts to get restored with Vida(); which increases the live +1
Thanks for your help!
This is the way the hearts look
My code uses spanish words.
PD: I know my code is a mess, but works for the other stuff.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine.UI;
public class DixonMovement : MonoBehaviour
{
public GameObject PildoraPrefab;
public float Speed;
public float JumpForce;
public AudioClip Golpe;
public AudioClip Salto;
public AudioClip Muerte;
public AudioClip Caida;
public GameObject[] Corazones;
private Rigidbody2D Rigidbody2D;
private Animator Animator;
private float Horizontal;
private bool Grounded;
private float LastShoot;
private int Health = 5;
public bool YaSono = false;
[Header("IFrame Stuff")]
public Color flashColor;
public Color regularColor;
public float flashDuration;
public int numberOfFlashes;
public Collider2D triggerCollider;
public SpriteRenderer mySprite;
float timer;
bool invencible = false;
private void Start()
{
Rigidbody2D = GetComponent<Rigidbody2D>();
Animator = GetComponent<Animator>();
}
// Update is called once per frame
private void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
invencible = false;
}
Horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
if (Horizontal < 0.0f) transform.localScale = new Vector3(-1.0f, 1.0f, 1.0f);
else if (Horizontal > 0.0f) transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
Animator.SetBool("Caminar", Horizontal != 0.0f);
Debug.DrawRay(transform.position, Vector3.down * 0.5f, Color.red);
if (Physics2D.Raycast(transform.position, Vector3.down, 0.5f))
{
Grounded = true;
}
else Grounded = false;
if (CrossPlatformInputManager.GetButtonDown("Jump") && Grounded)
{
Jump();
}
if (Input.GetKeyDown(KeyCode.W) && Grounded)
{
Jump();
}
if (Input.GetKey(KeyCode.Space) && Time.time > LastShoot + 0.25f)
{
Shoot();
LastShoot = Time.time;
}
if (CrossPlatformInputManager.GetButtonDown("Shoot") && Time.time > LastShoot + 0.50f)
{
Shoot();
LastShoot = Time.time;
}
/* if (CrossPlatformInputManager.GetButtonDown("Vertical") && Time.time > LastShoot + 0.50f)
{
Shoot();
LastShoot = Time.time;
}*/
if (transform.position.y <= -2)
{
Fall();
}
}
private void FixedUpdate()
{
Rigidbody2D.velocity = new Vector2(Horizontal * Speed, Rigidbody2D.velocity.y);
}
private void Jump()
{
Rigidbody2D.AddForce(Vector2.up * JumpForce);
Camera.main.GetComponent<AudioSource>().PlayOneShot(Salto);
}
private void Shoot()
{
Vector3 direction;
if (transform.localScale.x == 1.0f) direction = Vector3.right;
else direction = Vector3.left;
GameObject pastilla = Instantiate(PildoraPrefab, transform.position + direction * 0.40f, Quaternion.identity);
pastilla.GetComponent<Pastilla>().SetDirection(direction);
}
**public void Hit()
{
Health -= 1;
if (Health > 0)
{
StartCoroutine(FlashCo());
}
if (Health < 1)
{
Destroy(Corazones[0].gameObject);
}
else if (Health < 2)
{
Destroy(Corazones[1].gameObject);
}
else if (Health < 3)
{
Destroy(Corazones[2].gameObject);
}
else if (Health < 4)
{
Destroy(Corazones[3].gameObject);
}
else if (Health < 5)
{
Destroy(Corazones[4].gameObject);
}
if (Health > 0)
{
Camera.main.GetComponent<AudioSource>().PlayOneShot(Golpe);
}**
if (Health == 0)
{
Camera.main.GetComponent<AudioSource>().PlayOneShot(Muerte);
Animator.SetTrigger("Muerte");
if (Grounded == false)
{
Rigidbody2D.bodyType = RigidbodyType2D.Dynamic;
Rigidbody2D.gravityScale = 2;
}
else
{
Rigidbody2D.bodyType = RigidbodyType2D.Static;
}
}
}
public void Fall()
{
if (transform.position.y <= -1)
{
Rigidbody2D.AddForce(Vector2.up * 60);
if (!YaSono)
{
Camera.main.GetComponent<AudioSource>().PlayOneShot(Caida);
YaSono = true;
}
Animator.SetTrigger("Muerte");
Health = 0;
Destroy(Rigidbody2D, 2);
Destroy(Corazones[0].gameObject);
Destroy(Corazones[1].gameObject);
Destroy(Corazones[2].gameObject);
Destroy(Corazones[3].gameObject);
Destroy(Corazones[4].gameObject);
Invoke("RestartLevel", 2);
}
}
public void Vida()
{
if (Health >=5) { } else { Health += 1; }
}
public void Bounce()
{
Rigidbody2D.AddForce(Vector2.up * 300);
}
void Invencible()
{
timer = 1;
if (timer > 0)
{
invencible = true;
}
}
private IEnumerator FlashCo()
{
int temp = 0;
triggerCollider.enabled = false;
while (temp < numberOfFlashes)
{
mySprite.color = flashColor;
yield return new WaitForSeconds(flashDuration);
mySprite.color = regularColor;
yield return new WaitForSeconds(flashDuration);
temp++;
}
triggerCollider.enabled = true;
}
private void RestartLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
Instead of using Destroy(Corazones[0].gameObject) you could use Corazones[0].gameObject.setActive(false) or simply Corazones[0].setActive(false) since the array already contains GameObjects.
This would preserve the GameObject while all of its components and children would be inactivated including its Renderer which would make it disappear.
Then later when you need it you could reactivate it using Corazones[0].setActive(true).

Why is this Coroutine for my Weapon Reloading not working?

I have this code for a Weapon with reloading, and if I start to reload, switch to a different weapon, and the switch back to the weapon that should be reloading, The weapon doesn't reload, can't shoot, and will Display the AmmoDisplay of the previous weapons... any idea why? I tried setting the IEnumerator to public, but that didn't work either.
using UnityEngine;
using System.Collections;
using TMPro;
public class GunScript_SB : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public float impactForce = 30f;
public float fireRate = 15f;
public float maxAmmo = 10;
private float currentAmmo;
public float reloadTime = 3f;
private bool isReloading = false;
public Camera fpsCam;
public ParticleSystem muzzleFlash;
public GameObject impactEffect;
public TextMeshProUGUI ammunitionDisplay;
private float nextTimeToFire = 0;
void Start()
{
currentAmmo = maxAmmo;
}
void onEnable()
{
isReloading = false;
AmmoDisplay();
}
// Update is called once per frame
void Update()
{
if (isReloading)
return;
if (currentAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
if (Input.GetButtonDown("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
if (ammunitionDisplay != null)
{
AmmoDisplay();
}
if (Input.GetKeyDown(KeyCode.R) && currentAmmo < maxAmmo)
{
StartCoroutine(Reload());
}
}
public IEnumerator Reload()
{
isReloading = true;
Debug.Log("Reloading...");
yield return new WaitForSeconds(reloadTime);
currentAmmo = maxAmmo;
isReloading = false;
}
void Shoot()
{
muzzleFlash.Play();
currentAmmo--;
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
}
if (hit.rigidbody != null)
{
hit.rigidbody.AddForce(-hit.normal * impactForce);
}
GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impactGO, 1f);
}
}
void AmmoDisplay()
{
ammunitionDisplay.SetText(currentAmmo + " / " + maxAmmo);
}
}
Your coroutine could possibly still running after switching weapon. Add a referencing field and stop the coroutine before starting it again:
private Coroutine reloadCoroutine;
if (reloadCoroutine != null){
StopCoroutine(reloadCoroutine);
}
reloadCoroutine = StartCoroutine(Reload());

I am Having Trouble With This Error <Type or namespace definition, or end-of-file expected>

I am trying to add a double jump to my player but I have this error
and I am having problems with curly Brackets Because In The Begging Of The Code Must Contain = public class PlayerController: MonoBehaviour{
and end in }
the code is this if anyone that sees this knows C# And Can Help You Have My Thanks
using System.Collections;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private float moveSpeedStore;
public float speedMultiplier;
public float speedIncreaseMilestone;
private float speedIncreaseMilestoneStore;
private float speedMilestoneCount;
private float speedMilestoneCountStore;
public float jumpForce;
public float jumpTime;
private float jumpTimeCounter;
private Rigidbody2D myRigidbody;
private bool canDoubleJump;
public bool grounded;
public LayerMask whatIsGround;
public Transform groundCheck;
public float groundCheckSize;
private Collider2D myCollider;
private Animator myAnimator;
private bool stoppedJumping;
public GameManeger theGameManeger;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
myCollider = GetComponent<Collider2D>();
myAnimator = GetComponent<Animator>();
jumpTimeCounter = jumpTime;
speedMilestoneCount = speedIncreaseMilestone;
moveSpeedStore = moveSpeed;
speedMilestoneCountStore = speedMilestoneCount;
speedIncreaseMilestoneStore = speedIncreaseMilestone;
stoppedJumping = true;
}
void Update()
{
//grounded = Physics2D.IsTouchingLayers(myCollider, whatIsGround);
grounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckSize, whatIsGround);
if (transform.position.x > speedMilestoneCount)
{
speedMilestoneCount += speedIncreaseMilestone;
speedIncreaseMilestone = speedIncreaseMilestone * speedMultiplier;
moveSpeed = moveSpeed * speedMultiplier;
}
myRigidbody.velocity = new Vector2(moveSpeed, myRigidbody.velocity.y);
if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButtonDown(0))
{
if (grounded)
{
myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, jumpForce);
stoppedJumping = false;
}
}
if (Input.GetKey(KeyCode.Space) || Input.GetMouseButton(0) && !stoppedJumping)
{
if (jumpTimeCounter > 0)
{
myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, jumpForce);
jumpTimeCounter -= Time.deltaTime;
}
if (!grounded && canDoubleJump)
{
myRigidbody.velocity = new Vector2(myRigidbody.velocity.x, jumpForce);
stoppedJumping = false;
canDoubleJump = false;
}
}
if (Input.GetKeyUp(KeyCode.Space) || Input.GetMouseButtonUp(0))
{
jumpTimeCounter = 0;
stoppedJumping = true;
}
if (grounded)
{
jumpTimeCounter = jumpTime;
canDoubleJump = true;
}
myAnimator.SetFloat("Speed", myRigidbody.velocity.x);
myAnimator.SetBool("Grounded", grounded);
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "killbox")
{
theGameManeger.RestartGame();
moveSpeed = moveSpeedStore;
speedMilestoneCount = speedMilestoneCountStore;
speedIncreaseMilestone = speedIncreaseMilestoneStore;
}
}
}
``````
Check for any additional closing brackets } you might have added by mistake, or maybe a missing one, i'd suggest using an IDE as they are made to detect these types of mistakes.
I believe Chris Dunaway is correct. It looks like there's an extra curly brace in your code that pushed the last method out of the class.
So this (SO forced formatting):
[...]
myAnimator.SetFloat("Speed", myRigidbody.velocity.x);
myAnimator.SetBool("Grounded", grounded);
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "killbox")
{
theGameManeger.RestartGame();
moveSpeed = moveSpeedStore;
speedMilestoneCount = speedMilestoneCountStore;
speedIncreaseMilestone = speedIncreaseMilestoneStore;
}
}
}
Should be this:
[...]
myAnimator.SetFloat("Speed", myRigidbody.velocity.x);
myAnimator.SetBool("Grounded", grounded);
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "killbox")
{
theGameManeger.RestartGame();
moveSpeed = moveSpeedStore;
speedMilestoneCount = speedMilestoneCountStore;
speedIncreaseMilestone = speedIncreaseMilestoneStore;
}
}
}

Controlling swipe inputs in unity

I am practicing in Unity; I want to move an object to the right and left according to how I swipe. I have gotten the script so far but the problem occurs when I am playing it. It is setting the objects location to the center; swipe actions are working just fine. However, I don't want it to set the object to the center.
Script:
public class swipeTest : MonoBehaviour {
public SwipeManager swipeControls;
public Transform Player;
private Vector3 desiredPosition;
private void Update() {
if (swipeControls.SwipeLeft)
desiredPosition += Vector3.left;
if (swipeControls.SwipeRight)
desiredPosition += Vector3.right;
Player.transform.position = Vector3.MoveTowards
(Player.transform.position, desiredPosition, 0.5f * Time.deltaTime);
}
}
And Another
public class SwipeManager : MonoBehaviour {
private bool tap, swipeLeft, swipeRight, swipeUp, swipeDown;
private bool isDraging = false;
private Vector2 startTouch, swipeDelta;
public Vector2 SwipeDelta { get { return swipeDelta; } }
public bool Tap { get { return tap; } }
public bool SwipeLeft { get { return swipeLeft; } }
public bool SwipeRight { get { return swipeRight; } }
public bool SwipeUp { get { return swipeUp; } }
public bool SwipeDown { get { return swipeDown; } }
private void Update() {
tap = swipeLeft = swipeRight = swipeUp = swipeDown = false;
#region Standalone Inputs
if (Input.GetMouseButtonDown(0)) {
tap = true;
isDraging = true;
startTouch = Input.mousePosition;
}
else if (Input.GetMouseButtonUp(0)) {
isDraging = false;
Reset();
}
#endregion
#region Mobile Input
if (Input.touches.Length > 0) {
if (Input.touches[0].phase == TouchPhase.Began) {
isDraging = true;
tap = true;
startTouch = Input.touches[0].position;
}
else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled) {
isDraging = false;
Reset();
}
}
#endregion
// Calculate the distance
swipeDelta = Vector2.zero;
if (isDraging) {
if (Input.touches.Length > 0)
swipeDelta = Input.touches[0].position - startTouch;
else if (Input.GetMouseButton(0))
swipeDelta = (Vector2)Input.mousePosition - startTouch;
}
//Did we cross the distance?
if (swipeDelta.magnitude > 125) {
//Which direction?
float x = swipeDelta.x;
float y = swipeDelta.y;
if (Mathf.Abs(x) > Mathf.Abs(y)) {
//Left or right
if (x < 0)
swipeLeft = true;
else
swipeRight = true;
}
else {
// Up or down
if (y < 0)
swipeDown = true;
else
swipeUp = true;
}
Reset();
}
}
void Reset() {
startTouch = swipeDelta = Vector2.zero;
isDraging = false;
}
}
It seems like you never initialised desiredPosition in your code.
I did not successfully reproduce your issue, but theoretically I believe this should work. Please let us know if it helped.
Assuming no other forces act on the Player tranform (it won't be moved other than by this script):
public class swipeTest : MonoBehaviour {
private void Start() {
desiredPosition = Player.position;
}
}
Or if other forces act on Player you should update it every time:
public class swipeTest : MonoBehaviour {
private void Update() {
desiredPosition = Player.position;
if (swipeControls.SwipeLeft)
desiredPosition += Vector3.left;
if (swipeControls.SwipeRight)
desiredPosition += Vector3.right;
Player.transform.position = Vector3.MoveTowards
(Player.transform.position, desiredPosition, 0.5f * Time.deltaTime);
}
}

Categories

Resources